I have a familytree looking like this:
{
\"children\": [{
\"name\": \"bob\",
\"children\": [{
\"name\": \"sam\",
This is a proposal which iterates over the objects and uses backtracking for deleting the wanted node with the given name.
This solution keeps the original object and uses short circuit to prevent more than necessaray iterations.
It uses recusion as well.
function deleteFromTree(o, name) {
function getNode(a, i) {
if (a.name === name) {
index = i;
return true;
}
if (Array.isArray(a.children) && a.children.some(getNode)) {
if (~index) {
a.children.splice(index, 1);
index = -1;
}
return true;
}
}
var index = -1;
[o].some(getNode);
}
var tree = { "children": [{ "name": "bob", "children": [{ "name": "sam", "children": [{ "name": "mike", "children": [{ "name": "elias", "children": [] }, { "name": "rodriguez", "children": [] }] }] }] }] };
deleteFromTree(tree, 'sam');
document.write('' + JSON.stringify(tree, 0, 4) + '
');