After referring to this plunker https://plnkr.co/edit/CIGAA5BmiKU4hCMsOaIB?p=preview, I now require dynamic array operations.
[
{
title: 'Menu 1',
id :1,
hide : true,
children: [],
},
{
title: 'Menu 2',
hide : true,
id :2,
children: [{
title: 'Sub Menu 2',
hide : true,
id :3,
children: [{
title: 'Sub Sub Menu 2',
hide : true,
id :4,
children: [{
title: 'Sub Sub Menu 2, Sibling 1',
hide : true,
id :6,
children: []
},
{
title: 'Sub Sub Sub Menu 2, Sibling 2',
hide : true,
id :12,
children: []
}]
}]
}]
},
{
title: 'Menu 3',
hide : true,
id :14,
children: []
}
];
My current task is to push children into the object with id 6 and update the entire object after each operation.
I am working with Angular 5.
The method I am using is as follows:
find(id, items,newData) {
var i = 0, found;
for (; i < items.length; i++) {
if (items[i].id === id) {
items[i].children=newData;
return items;
} else if (_.isArray(items[i].children)) {
found = this.find(id, items[i].children,newData);
if (found) {
return false;
}
}
}
}
In this code, newData refers to the array that needs to be added, while items represent the main object that should be updated after an addition.
Please point out any mistakes in my approach. Additionally, if an element with id 3 has children with id 4, they should not be pushed under the same parent id.
All objects share a similar structure, where newData also contains children.