从find

时间:2018-12-20 09:41:09

标签: javascript

我试图了解如何遍历无限嵌套的对象

为简单起见,这就是我所做的

let infiniteArray = [ 
    { 
      name: "Jack",
      age: "98" ,
      profession: "doctor",
      children: [
                  {
                    name: "Varun",
                    age: "80",
                    profession: "scientist",
                    children: [
                                {
                                   name: "Ishan",
                                   age: "62",
                                   profession: "teacher"
                                }
                            ]
                    }
                ]
        }
]


function isTheItem(item) {
   if (item["profession"] === "teacher") return item
    return false
 }


 function walk(collection) {
    return collection.find(item => isTheItem(item) || walk(item.children));
  }

现在的问题是,由于我正在使用递归,因此无限数组(在某个时候是正确的)将返回infiniteArray,我希望它只返回与之对应的名称

  name: "Ishan",

我该如何实现?

1 个答案:

答案 0 :(得分:1)

您需要按以下方式更新walk函数。

要找到第一个匹配项

let infiniteArray = [{name:"Jack",age:"98",profession:"doctor",children:[{name:"Varun",age:"80",profession:"scientist",children:[{name:"Ishan",age:"62",profession:"teacher"}]}]}];

function isTheItem(item) {
   if (item["profession"] === "teacher") return item
    return false
 }

function walk(collection) {
  let result;
  for (let item of collection) {
    if(isTheItem(item)) result = item;
    else result = walk(item.children);
    if(result) break;
  }
  return result;
}

console.log(walk(infiniteArray));

或者如果您需要收集所有可能的匹配项

let infiniteArray = [{name:"Jack",age:"98",profession:"doctor",children:[{name:"Varun",age:"80",profession:"scientist",children:[{name:"Ishan",age:"62",profession:"teacher"}]}]}];

function isTheItem(item) {
   if (item["profession"] === "teacher") return item
    return false
 }

function walk(collection, result = []) {
  collection.forEach(item => {
    if(isTheItem(item)) result.push(item);
    else walk(item.children, result);
  });
  return result;
}

console.log(walk(infiniteArray));