查找并替换数组中的对象(基于id)

jj0*_*008 3 javascript arrays object ecmascript-6

这里有一点难题...我想循环allItems并返回allItems但替换任何newItems匹配其ID.如何查找匹配项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'
  }
]
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试了什么:

for(let i = 0; i < allItems.length; i++) {
  if(newItems.indexOf(allItems[i].id) > -1){
    allItems[i] = newItems
  }
}
Run Code Online (Sandbox Code Playgroud)

如何获取对象的位置newItems然后将其替换为allItems

jo_*_*_va 6

使用Array.mapArray.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);
Run Code Online (Sandbox Code Playgroud)

这甚至可以通过使用逻辑来缩短,或者在调用find返回时返回原始项undefined:

const result = allItems.map(x => newItems.find(({ id }) => id === x.id) || x);
Run Code Online (Sandbox Code Playgroud)

关于您的代码,您不能使用,indexOf因为它只比较数组和对象的原始值或引用.