[英]How to change the nested array object by checking key `status` in javascript
I have a object obj
, has nested array of object children
, loop through each object and我有一个 object
obj
,嵌套了 object 个children
的数组,遍历每个 object 和
check status and remove the object if status is deleted
.检查状态并删除 object 如果状态被
deleted
。
I have a code below, but partial works and each nested array may/maynot have any number children
.我在下面有一个代码,但部分有效,每个嵌套数组可能/可能没有任何数量的
children
。
How to remove based on condition in javascript如何根据条件删除 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"}
]
}
]
}
]
Expected Output:预计 Output:
[
{
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"}
]
}
]
}
]
You can use recursion for your solution.您可以为您的解决方案使用递归。 Here it is:
这里是:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.