从嵌套结构中删除项目

时间:2018-11-08 09:26:19

标签: javascript

我有以下对象:

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

我希望能够使用id属性来删除特定的对象(例如,删除ID为4的对象)。我显然可以使用arr.findIndex找到该对象,但是如何将其从封闭数组中删除呢?我正在努力寻找如何获取父数组,以便可以将其删除。同样,我知道如何使用splice从数组中删除,但我遇到的问题是如何以编程方式执行此操作,因此可以从上述嵌套结构中的任何位置删除任何项目。

1 个答案:

答案 0 :(得分:1)

尝试关注

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);