我有一个对象数组,我想过滤,然后返回过滤后的数组,但与另一个数组比较,看是否需要替换它。
比如我想通过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/