I need to find if item exist in deep nested array.
example of array
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 find if has property with name hasChild find item and set it on false.
After looping i need to get array like ->
example of array
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;
}
});
CodePudding user response:
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);
CodePudding user response:
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.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.
