我这里有一个小难题……我想循环遍历allItems
数组,并返回allItems
,但是如果遇到任何与其id匹配的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
中?