简体   繁体   English

查找项目是否存在于深层嵌套的子数组中?

[英]Find item if exist in deep nested children array?

I need to find if item exist in deep nested array.我需要查找项目是否存在于深层嵌套数组中。

Example:例子:

let arr = [
  {
   id: 1 ,
   title : 'Test' ,
   children: 
  [
    {id: 1 , title: 'Title' , hasChild : true },
    {id: 1 , title: 'Title' , hasChild : false },
    {id: 1 , title: 'Title' },
  ] 
 },
]

I need to looping thought arr.children and trying to find if it has a property with name hasChild find item and set it on false.我需要循环思考arr.children并尝试查找它是否具有名称为hasChild的属性 find item 并将其设置为 false。

After looping I need to get an array like :循环后我需要得到一个数组,如

let arr = [
  {
   id: 1 ,
   title : 'Test' ,
   children: 
  [
    {id: 1 , title: 'Title' , hasChild : false }, //here is changed hasChild to false
    {id: 1 , title: 'Title' , hasChild : false },
    {id: 1 , title: 'Title' },
  ] 
 },
]

I am find way but i need better solution:我找到了方法,但我需要更好的解决方案:

    arr.map(it) => {
      if (it.hasChild) {
        it.dashCheck = false; 
      }
    });

You can use recursive functions to make operations on inifitely nested objects/arrays etc.您可以使用递归函数对无限嵌套的对象/数组等进行操作。

function recursiveUpdate(array, index) {
  const element = array[index];
  if(!element) return;
  if(Object.keys(element).indexOf('children') > -1) {
    element.hasChild = true;
    recursiveUpdate(element['children'], 0);
  } else {
    element.hasChild = false;
    recursiveUpdate(array, index+1);
  }
}

recursiveUpdate(arr, 0);

If the structure of arr is always like the one you mentioned in your question, you could simple iterate over the children by using the forEach method of the Array class:如果arr的结构总是像您在问题中提到的那样,您可以使用Array class 的forEach方法简单地遍历children

arr.forEach(item => {
  item.children.forEach(child => {
    child.hasChild = child.hasChild === true ? false : child.hasChild;
  });
});

Note : This will alter the original array and not create a copy with the altered value for hasChild .注意:这将更改原始数组,并且不会使用更改后的hasChild值创建副本。

Demo:演示:

 let arr = [{ id: 1, title: 'Test', children: [ {id: 1, title: 'Title', hasChild: true }, {id: 1, title: 'Title', hasChild: false }, {id: 1, title: 'Title' }, ] }]; arr.forEach((obj) => { obj.children.forEach((childObj) => { if (childObj.hasChild) { childObj.hasChild = false; } }); }); console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM