gpt4 book ai didi

javascript - 通过键值从 Javascript 中的嵌套数组对象中删除项目

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

我有这样的对象:

{
"id": 1,
"name": "first",
"sections": [
{
"id": 1,
"title": "First section",
"contents": [
{
"id": "123",
"title": "Sample title 1",
"description": "<html>code</html>",
},
{
"id": "124",
"title": "Sample title 2",
"description": "<html>code</html>"
},
{
"id": "125",
"title": "Some other sample",
"description": "<html>code</html>"
}
]
},
{
"id": 2,
"title": "Second section",
"contents": [
{
"id": "126",
"title": "Sample title 126",
"description": "<html>code</html>"
},
{
"id": "127",
"title": "Sample title 127",
"description": "<html>code</html>"
}
]
}
]
}

我想通过其 id 从内容数组中删除特定对象(所有这些 id 都是唯一的)。

我可以很容易地找到我想要删除的元素,但我无法找到这个元素稍后要在哪个部分进行拼接。

obj.sections.forEach(function(section) {
section.contents.forEach((content) => {
if (content.id == 125) {
console.log(content)
console.log(section)
}
})
})

在上面的代码中,console.log(sections) 返回未定义。如何获取包含具有特定 id 的内容数组的节数组中的位置。例如,id: 125 将返回节位置 0,因此我可以使用 splice 删除该元素。

如果我的方法完全错误,请指出我正确的方向,谢谢:)

最佳答案

您可以使用.filter()而不是 .splice().filter() 将保留您返回 true 的所有项目,并丢弃您返回 false 的项目。因此,如果当前部分内容的对象的 id 等于您要删除的对象,则可以返回 false 来删除它,否则返回 true > 保留该项目。您可以将其与 .map() 一起使用将每个节对象映射到具有更新内容数组的新对象:

const obj = { "id": 1, "name": "first", "sections": [ { "id": 1, "title": "First section", "contents": [ { "id": "123", "title": "Sample title 1", "description": "<html>code</html>", }, { "id": "124", "title": "Sample title 2", "description": "<html>code</html>" }, { "id": "125", "title": "Some other sample", "description": "<html>code</html>" } ] }, { "id": 2, "title": "Second section", "contents": [ { "id": "126", "title": "Sample title 126", "description": "<html>code</html>" }, { "id": "127", "title": "Sample title 127", "description": "<html>code</html>" } ] } ] };

const idToRemove = 125;
obj.sections = obj.sections.map(
sec => ({...sec, contents: sec.contents.filter(({id}) => id != idToRemove)})
);

console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore */

关于javascript - 通过键值从 Javascript 中的嵌套数组对象中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60487009/

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