2017-04-26 118 views
1

如何递归搜索嵌套对象以查找我提供的对象引用的路径?Javascript - 在嵌套对象中查找对象引用的路径

我的原始对象看起来像:

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

我想调用的函数findDeepAndStorePath(a, obj)这将找到该对象的引用和路径,将其存储在索引诸如数组:[“B”, 0,1,2]。

+0

你应该写你自己与事件发射器将走混合数据 – num8er

+0

对不起,你介意详细阐述了这个代码? –

回答

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

+2

好和优雅的答案! –

+0

这太棒了!谢谢! –

1

你可以使用Object.keys并检查值。如果找到,则返回实际路径并停止迭代。如果不是,则检查所有可能的路径。

此建议尊重数组键的数字键。

function findPath(a, obj) { 
 
    function iter(o, p) { 
 
     return Object.keys(o).some(function (k) { 
 
      result = p.concat(Array.isArray(o) ? +k : k); 
 
      return o[k] === a || o[k] && typeof o[k] === 'object' && iter(o[k], result); 
 
     }); 
 
    } 
 
    var result; 
 
    return iter(obj, []) && result || undefined; 
 
} 
 

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

 
console.log(findPath(5, obj));  // ["a", 2, "o"] 
 
console.log(findPath("str", obj)); // ["b", 1, 0, "bb", 1] 
 
console.log(findPath(42, obj)); // undefined
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

非常好!与所选答案一样好!谢谢! –