这里有点困惑...我想遍历 allItems
并返回 allItems
但替换为匹配的任何 newItems
它的编号。如何在 id
上查找匹配项,然后将其替换为数组中的正确对象?
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'
}
]
到目前为止我尝试了什么:
for(let i = 0; i < allItems.length; i++) {
if(newItems.indexOf(allItems[i].id) > -1){
allItems[i] = newItems
}
}
如何获取对象在newItems
中的位置,然后将其替换到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
时,甚至可以通过使用逻辑 or 返回原始项目来缩短此时间:
const result = allItems.map(x => newItems.find(({ id }) => id === x.id) || x);
关于您的代码,您不能使用 indexOf
,因为它仅在数组和对象的情况下比较原始值或引用。
关于javascript - 查找和替换数组中的对象(基于 id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876239/