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.
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;
}
});
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);
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);
Edit: Seems like the question was altered after I gave my answer. Updated my answer to reflect this.
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 => {
// Edit: Revised solution
if (child.hasChild === true) {
child.hasChild = false;
}
// Edit: Previous solution
// 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.