Reputation: 3103
I have an array of objects with an unlimited number of nested children objects like this:
var items = [
{
id: 1,
name: 'Item 1',
children: [
{
id: 2,
name: 'Item 2',
children: [],
}
]
},
{
id: 2,
name: 'Item 2',
children: [],
},
{
id: 3,
name: 'Item 3',
children: [
{
id: 1,
name: 'Item 1',
children: [
id: 2,
name: 'Item 2',
children: [],
]
}
]
}
];
I want to update every occurrence of object with id 2
to have a name of "This is a cool object".
I'm not sure if this needs recursion or if some type of find and replace will do.
var newObject = {
id: 2,
name: 'This is a cool object',
children: []
}
I want to replace every occurrence of any object with id 2 with the new object (regardless of the rest of the objects contents).
I tried looping through but then realized that it could potentially be unlimited levels deep.
Upvotes: 2
Views: 72
Reputation: 27202
Try this single line of code with Array filter() method.
function findID(items) {
return items.filter(obj => (obj.id === 2)?obj.name='This is a cool object':findID(obj.children));
}
var res = findID(items);
Working Demo
var items = [
{
id: 1,
name: 'Item 1',
children: [
{
id: 2,
name: 'Item 2',
children: [],
}
]
},
{
id: 2,
name: 'Item 2',
children: [],
},
{
id: 3,
name: 'Item 3',
children: [
{
id: 1,
name: 'Item 1',
children: [
{
id: 2,
name: 'Item 2',
children: [],
}
]
}
]
}
];
function findID(items) {
return items.filter(obj => (obj.id === 2)?obj.name='This is a cool object':findID(obj.children));
}
console.log(findID(items));
Upvotes: 1
Reputation: 33726
With recursion.
var items = [ { "id": 1, "name": "Item 1", "children": [ { "id": 2, "name": "Item 2", "children": [] } ] }, { "id": 2, "name": "Item 2", "children": [] }, { "id": 3, "name": "Item 3", "children": [ { "id": 1, "name": "Item 1", "children": [{ "id": 2, "name": "Item 2", "children": [] }] } ] }];
function loop(array, targetId) {
array.forEach((e) => {
if(e.id === targetId) {
e.name = 'This is a cool object';
}
if (e.children && e.children.length > 0) {
loop(e.children, targetId);
}
});
}
loop(items, 2);
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3