gpt4 book ai didi

javascript - 如何通过 id 删除子对象并使用过滤器检索父对象

转载 作者:行者123 更新时间:2023-11-28 12:13:27 25 4
gpt4 key购买 nike

我试图通过仅通过不匹配来删除其子 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);

这里出了什么问题,或者有人告诉我正确的方法?

寻找:

  1. 如果 id 与 rm 相同,则需要删除博客,且父级必须存在其他子级。

  2. 需要删除父级,然后删除子级,以防不存在子级(博客)。

Live Demo

最佳答案

循环访问父级列表,并在该循环内首先尝试删除具有给定 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;
})

关于javascript - 如何通过 id 删除子对象并使用过滤器检索父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55623500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com