我试图通过不匹配的方式删除父ID来过滤父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);
这有什么问题,或者有人向我展示了正确的方法?
寻找:
如果ID与rm相同,则需要删除该博客,并且其父级必须有其他子级。
需要删除父级,删除子级后,以防不存在任何子级(博客)。
答案 0 :(得分:4)
浏览父母列表,然后在该循环中,尝试首先删除具有给定ID的博客。完成此操作后,您可以检查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;
})
答案 1 :(得分:2)
我认为下面的代码就是您想要的
var result = objects.map(value => {
const blog = value.blog.filter(blog => blog.id !== rm);
if(blog.length === 0) {
return;
}
value.blog = blog;
return value;
}).filter(item => item);
答案 2 :(得分:0)
var result = objects.map(parent => {
parent.blog = parent.blog.filter(child => child.id !== rm);
return parent}).filter(parent => parent.blog && parent.blog.length > 0);