Given an array of objects like this:
var items = [{
id: 1
}, {
id: 2,
child: {
id: 3
}
}, {
id: 4,
child: {
id: 5,
child: {
id: 6
}
}
}];
I need a method to remove an item at any level. This code does what I want, but is there a better way?
Initially I tried doing it with one recursive function, but couldn't get that to work.
var removed = removeItems(items, 5);
print(removed);
function removeItems(items, id) {
items.forEach(function(item, index, allItems) {
if (item.id === id) {
items.splice(index, 1);
}
if (item.child) {
item = testChild(item, item.child, id);
}
});
return items;
}
function testChild(parent, child, id) {
if (child.id === id) {
delete parent.child
return parent;
} else {
if (child.child) {
return testChild(child, child.child, id);
}
return parent;
}
}
function print(obj) {
document.querySelector('#out').innerHTML += JSON.stringify(obj, null, 2);
}
jsfiddle: https://jsfiddle.net/syvf46uL/12/