我试图过滤父程序,只通过不匹配来删除它的子id。如果不存在子项,则应移除父级。
我试过这样做,但不管用。
var rm = 7;
var objects = [
{
name: "parent1",
id: 1,
blog: [
{
name: "child1",
id: 1
},
{
name: "child2",
id: 2
}
]
},
{
name: "parent2",
id: 2,
blog: [
{
name: "child3",
id: 3
},
{
name: "child4",
id: 4
}
]
},
{
name: "parent3",
id: 3,
blog: [
{
name: "child5",
id: 5
},
{
name: "child6",
id: 6
}
]
},
{
name: "parent4",
id: 3,
blog: [
{
name: "child6",
id: 7
}
]
},
]
var result = objects.filter(value => {
if(!value.blog) return;
return value.blog.some(blog => blog.id !== rm)
})
console.log(result);这里有什么问题,还是有人给我看了正确的方法?
寻找:
发布于 2019-04-11 01:58:19
循环遍历父母列表,在该循环中,首先尝试删除带有给定id的blog。完成此操作后,您可以检查blogs属性是否为空,如果为空,则将其过滤掉:
// We're going to filter out objects with no blogs
var result = objects.filter(value => {
// First filter blogs that match the given id
value.blog = value.blog.filter(blog => blog.id !== rm);
// Then, if the new length is different than 0, keep the parent
return value.blog.length;
})发布于 2019-04-11 02:09:00
var result = objects.map(parent => {
parent.blog = parent.blog.filter(child => child.id !== rm);
return parent}).filter(parent => parent.blog && parent.blog.length > 0);https://stackoverflow.com/questions/55623500
复制相似问题