gpt4 book ai didi

javascript - 如何根据字符串匹配拉取嵌套对象?

转载 作者:行者123 更新时间:2023-11-30 09:11:51 26 4
gpt4 key购买 nike

activePath 会根据 api 调用动态变化,如何根据嵌套对象中匹配的 activePath 字符串拉取对象?

路径示例:Drug/GetRefills 在这种情况下它应该推送 data.Drug.getRefills 如果路径是 Payment/getAccount 它应该推送 data.Payment.getAccount

主要.js

const data = 
[{
id: 11,
name: "Drug",
children: [{
id: 12,
name: "getRefills"
}, {
id: 13,
name: "getDetails"
}]
}, {
id: 14,
name: "Payment",
children: [{
id: 15,
name: "getAccount"
}, {
id: 16,
name: "getAccountDetails"
}]
}]


function getModelData(data){
var activePath = "Drug/GetRefills";
var _interfaces = [];
$.each(data, function(id, item){
if (activePath.toLowerCase().includes(item.name)) {
console.log('OBJ', item);
_interfaces.push(item); // it should push getrefills object into interfaces
}
});

return _interfaces;
}

最佳答案

可以使用递归来查找对象(类似于DFS):

const data = [{
id: 11,
name: "Drug",
children: [{
id: 12,
name: "getRefills"
}, {
id: 13,
name: "getDetails"
}]
}, {
id: 14,
name: "Payment",
children: [{
id: 15,
name: "getAccount"
}, {
id: 16,
name: "getAccountDetails"
}]
}];


function getModelData(path) {
function find(arr, [key, ...rest]) {
const obj = arr.find(o => o.name === key);
if (!obj) return null;
return rest.length ? find(obj.children || [], rest) : obj;
}

return find(data, path.split('/'));
// Instead of returning, add the found object to _interfaces
}

console.log(getModelData('Drug/getRefills'));
console.log(getModelData('Drug/getRefillsss'));
console.log(getModelData('Payment/getAccountDetails'));

关于javascript - 如何根据字符串匹配拉取嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com