gpt4 book ai didi

javascript - 以不可变的方式删除嵌套数组中的对象

转载 作者:行者123 更新时间:2023-12-01 15:52:47 26 4
gpt4 key购买 nike

这就是我的数据的样子:

categories = [
{
name: ""
products: [
{
id: 1,
...
},
{
id: 2,
...
}
]
},
{
name: ""
products: [
{
id: 3,
...
},
{
id: 4,
...
}
]
},
...
]

我想删除 id 为 1 的产品,这是我的代码:

categories.map(category => category.products.filter(product => product.id !== 1))

这是正确的代码吗?如果是这样,我如何创建一个新数组并使用新值设置它?

最佳答案

您已经很接近了,但您的代码正在将类别对象替换为其过滤后的 products 数组,从而丢失了其余的对象属性。您需要复制每个 category 对象及其 products 数组,这通常通过扩展符号来完成:

updatedCategories = categories.map(category => ({
...category,
products: category.products.filter(product => product.id !== 1)
}));

关于javascript - 以不可变的方式删除嵌套数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61102584/

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