gpt4 book ai didi

Javascript - 在嵌套对象中查找对象引用的路径

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

我如何递归搜索嵌套对象以找到我提供的对象引用的路径?

我原来的对象是这样的:

a = {
b: [
{ children: [...more objects] },
{ children: [] }
etc..
],
c: [
{ children: [...more objects] },
{ children: [] }
etc..
]
}

我想调用一个函数findDeepAndStorePath(a, obj),它会找到对象引用并将它的路径存储在索引数组中,例如:['b', 0, 1, 2]。

最佳答案

function findPath(a, obj) {
for(var key in obj) { // for each key in the object obj
if(obj.hasOwnProperty(key)) { // if it's an owned key
if(a === obj[key]) return key; // if the item beign searched is at this key then return this key as the path
else if(obj[key] && typeof obj[key] === "object") { // otherwise if the item at this key is also an object
var path = findPath(a, obj[key]); // search for the item a in that object
if(path) return key + "." + path; // if found then the path is this key followed by the result of the search
}
}
}
}

var obj = {
"a": [1, 2, {"o": 5}, 7],
"b": [0, [{"bb": [0, "str"]}]]
};

console.log(findPath(5, obj));
console.log(findPath("str", obj).split(".")); // if you want to get the path as an array you can simply split the result of findPath

关于Javascript - 在嵌套对象中查找对象引用的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43636000/

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