gpt4 book ai didi

javascript - 过滤对象数组然后替换

转载 作者:行者123 更新时间:2023-11-30 19:46:49 24 4
gpt4 key购买 nike

我有一个对象数组,我想过滤,然后返回过滤后的数组,但与另一个数组比较,看是否需要替换它。

比如我想通过category_id = 2过滤allItems,然后根据newItems数组,我想返回过滤后的数组,但更新项位于 newItems 中(如果存在)。

allItems = [
{
'id': 1,
'category_id': 2,
'text': 'old',
'child': [
{
'id': 2,
'category_id': 2,
'text': 'old'
}
]
},
{
'id': 3,
'category_id': 3,
'text': 'old'
}
]


newItems = [
{
'id': 2,
'category_id': 2,
'text': 'new'
}
]

所以我想返回:

results = [
{
'id': 2,
'category_id': 2,
'text': 'new'
},
{
'id': 3,
'category_id': 2,
'text': 'old'
},
]

现在,我有过滤部分,但我不确定如何与另一个数组进行比较并替换为更新后的项目。

return this.allItems.filter( (item) => {
return item.category_id == 2
})

最佳答案

使用 filter其次是 .map , 用新项目替换项目(如果需要):

const allItems = [
{
'id': 1,
'category_id': 1,
'text': 'old'
},
{
'id': 2,
'category_id': 2,
'text': 'old'
},
{
'id': 3,
'category_id': 2,
'text': 'old'
}
];
const newItems = [
{
'id': 2,
'category_id': 2,
'text': 'new'
}
];

const newItemsById = newItems.reduce((a, item) => {
a[item.id] = item;
return a;
}, {});

const output = allItems
.filter(({ category_id }) => category_id === 2)
.map((item) => newItemsById[item.id] ? newItemsById[item.id] : item);
console.log(output);

另请注意,您的 'id': <number> allItems 中的键值对需要后跟逗号,当后跟另一个键值对时,语法才有效。

关于javascript - 过滤对象数组然后替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858571/

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