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

Dra*_*scu 3 javascript

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

我的原始对象看起来像:

a = {
 b: [
  { children: [...more objects] },
  { children: [] }
  etc..
 ],
 c: [
  { children: [...more objects] },
  { children: [] }
  etc..
 ]
}
Run Code Online (Sandbox Code Playgroud)

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

ibr*_*rir 8

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
Run Code Online (Sandbox Code Playgroud)