-1

I have the following object:

{
  id: 1,
  children: [
     {id: 2},
     {id: 3, children: [
        {id: 4 }
     ]}
  ]
}

I want to be able to remove a specific object by using the id property (e.g. remove the object with an id of 4). I can obviously find the object by using arr.findIndex but how do I remove it from the enclosing array? I'm struggling with finding how to get the parent array so I can remove it. Again I know how to remove from an array using splice but the problem I'm having is how to do this programmatically so I can remove any item from anywhere in a nested structure as above.

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111

1 Answers1

1

Try following

let obj = {id: 1,children: [{id: 2},{id: 3, children: [{id: 4 }]}]};

/* o is object or sub-object
 * k is id to be deleted
 * p is parent of object, same as o for first time
 * index is the index of item in the children array */
function removeKey(o, k, p=o, index) {
  if(o.id === k) { // if this is the object that needs to be removed
    // For first level object, make the object empty
    if(o.id === p.id) {delete o.children; delete o.id}
    // For others remove it from the children array
    else p.children.splice(index,1);
  } else if(o.children) { // if the object is not a match and has children
    // iterate over the children and check and remove key
    for (let i = 0; i < o.children.length; i++) {
      if(removeKey(o.children[i], k, o, i)) break;
    }
  }
}

removeKey(obj, 4);
console.log(obj);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59