I'm looping through a nested object of objects, looking for a specific object and if I'm I find it, I do stuff. I can get it working for the first nest, but any nest after that I get an undefined value.
let myObj = [{
id: 1,
children: [{
id: 1.1,
children: []
},
{
id: 1.2,
children: []
}
]
},
{
id: 2,
children: [{
id: 2.1,
children: []
},
{
id: 2.2,
children: []
}
]
}
]
function addToObj(itemToAdd, parentId, obj) {
for (let i = 0; i < obj.length; i++) {
const item = search(obj[i], parentId);
console.log(item); // undefined
if (item) {
item.children = item.children.concat(itemToAdd);
break;
}
}
function search(obj, id) {
if (obj.id === id) {
console.log(obj); // defined (obj with id of 2.1), but returns undefined?
return obj;
}
for (let i = 0; i < obj.children.length; i++) {
search(obj.children[i], id);
}
}
return obj;
};
const itemToAdd = {
id: 100,
}
addToObj(itemToAdd, 2.1, myObj);
The function in the above snippet loops through the object, looking for a specific item. If it finds the item it will insert an object into that items children property.
if (obj.id === id)is false, there is no return value