在数组中查找并替换对象(基于ID) [英] Find and replace object in array (based on id)
问题描述
在这里有点困惑...我想遍历allItems
并返回allItems
,但用与其ID相匹配的任何newItems
代替.如何在id
上查找匹配项,然后将其替换为数组中的正确对象?
Got a bit of a puzzle here...I want to loop through allItems
and return allItems
but replace with any newItems
that matches its id. How can I look for a match on id
and then replace it with the correct object into the array?
const allItems = [
{
'id': 1,
'category_id': 1,
'text': 'old',
},
{
'id': 2,
'category_id': 1,
'text': 'old'
}
]
const newItems = [
{
'id': 1,
'category_id': 1,
'text': 'new',
'more_info': 'abcd'
},
{
'id': 2,
'category_id': 1,
'text': 'new',
'more_info': 'abcd'
}
]
到目前为止我尝试过的事情:
What I tried so far:
for(let i = 0; i < allItems.length; i++) {
if(newItems.indexOf(allItems[i].id) > -1){
allItems[i] = newItems
}
}
如何获取对象在newItems
中的位置,然后将其替换为allItems
?
How can I get the position of the object in newItems
and then replace it into allItems
?
推荐答案
使用 Array.map
和 Array.find()
:
const allItems = [
{ 'id': 1, 'category_id': 1, 'text': 'old' },
{ 'id': 2, 'category_id': 1, 'text': 'old' }
];
const newItems = [
{ 'id': 1, 'category_id': 1, 'text': 'new', 'more_info': 'abcd' },
{ 'id': 2, 'category_id': 1, 'text': 'new', 'more_info': 'abcd' }
];
const result = allItems.map(x => {
const item = newItems.find(({ id }) => id === x.id);
return item ? item : x;
});
console.log(result);
甚至可以通过使用逻辑或在调用find
返回undefined
时返回原始项目来缩短此时间:
This can even be shortened by using a logical or to return the original item when the call to find
returns undefined
:
const result = allItems.map(x => newItems.find(({ id }) => id === x.id) || x);
关于代码,您不能使用indexOf
,因为它仅比较原始值或在数组和对象情况下的引用.
Regarding your code, you can't use indexOf
since it only compares primitive values or references in the case of arrays and objects.
这篇关于在数组中查找并替换对象(基于ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!