繁体   English   中英

如何在深度嵌套数组中循环递归? JS

[英]How to loop with recursion in deep nested array ? JS

我需要遍历深层 arrays,并更改一些值

arrays 示例 ->

let arr = 
[{ 
  id: 1 ,
  name : "Test 1 " ,
  title : "title 1 " , 
  hasChild : false,
  children :
  [
  { id: 2 , name : "test 2"  , title : 'title 2', hasChild true, children: [] },
  { id: 3 , name : "test 3"  , title : 'title 3', hasChild false, children: [] },
  { id: 4 , name : "test 4"  , title : 'title 4', hasChild false , children : 
  [
     id: 1 ,
     name : "Test 1 " ,
     title : "title 1 " , 
     hasChild : true,
  ]},
  ]
 },
]

循环后,我需要有一个相同的列表,但在每个将hasChild设置为 false 的数组中。

我正在尝试:

arr.children.forEach(item => item.children.hasChild = false)

但我还需要循环思考儿童 - >儿童列表,并设置儿童儿童儿童假......

这里可能不止这个儿童系列

我需要为每个孩子设置 false 。

const setHasChildToFalse = (arr) => {
  arr.forEach(item => {
    item.hasChild = false;
    if (item.children.length > 0) {
      setHasChildToFalse(item.children);
    }
  });
}
console.log(arr);

暂无
暂无

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

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