如何通过检查JavaScript中的键`status`来更改嵌套数组对象

时间:2020-09-23 08:07:44

标签: javascript arrays loops object

我有一个对象obj,具有对象children的嵌套数组,遍历每个对象,然后

检查状态并删除状态为deleted的对象。

我在下面有一个代码,但是部分工作并且每个嵌套数组可能/可能没有任何数字children

如何根据javascript中的条件删除

removeList =(obj)=>{
  if (obj.length > 0) {
    var result = obj.map(e => {
      if('children' in e)
        e.children = e.children.map(child => {
          if ('children' in child) 
            child.children = child.children.filter(c =>
              c['status'] !== "Deleted"
            );
            return child;
        });      
      return e
    });
    return result;
  }


}
console.log(this.removeList);
var obj = [
  {
   id:1,
   children: [
     {id:1, name: "grocery", status:"active",children:[{id:4, name:"lentils", status:"active"}]},
     {id:2, name: "fruits", status:"deleted"},
     {id:3, name: "coffee", status:"inactive",
       children: [
        {id:6, name:"vegetables", status:"inactive"},
        {id:7, name:"greens", status:"deleted"}
       ]
     }
   ]
  }
]

预期输出:

[
  {
   id:1,
   children: [
     {id:1, name: "grocery", status:"active",children:[{id:4, name:"lentils", status:"active"}]},
     {id:3, name: "coffee", status:"inactive",
       children: [
        {id:6, name:"vegetables", status:"inactive"}
       ]
     }
   ]

  }
]

1 个答案:

答案 0 :(得分:3)

您可以将递归用于您的解决方案。在这里:

var obj = [
  {
   id:1,
   children: [
     {id:1, name: "grocery", status:"active",children:[{id:4, name:"lentils", status:"active"}]},
     {id:2, name: "fruits", status:"deleted"},
     {id:3, name: "coffee", status:"inactive",
       children: [
        {id:6, name:"vegetables", status:"inactive"},
        {id:7, name:"greens", status:"deleted"}
       ]
     }
   ]
  }
]

removeList =(obj)=>{
  if (obj.length > 0) {
    var result = []
    obj.forEach(e => {
      if(e.status !== "deleted") { 
        if(e.children && e.children.length > 0) { e.children = removeList(e.children); }
      
        result.push(e) 
      }
    });
    return result;
  }


}
console.log(removeList(obj));