简体   繁体   中英

How to loop with recursion in deep nested array ? JS

I need to loop through the deep arrays, and change some value

example of 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,
  ]},
  ]
 },
]

after looping i need to have a same list but in every array where have a hasChild set to false.

I am try with:

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

But i need also to loop thought children - > children list and also set to children children children false...

There may be many more than this children's series here

I need to set false for every children.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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