首页 > 解决方案 > 从对象数组中查找和更改特定项目

问题描述

我正在处理一个像

arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. 现在我想给数组提供条件,就像我在数组中得到 id 'fifth' 一样,数组将变为

arr = [{id:'first',name:'John'},{id:'sixth',name:'Kat'},{id:'eitghth',name:'Isa'}]

就像只修改了项目的一部分。我怎么能在js中做到这一点?

标签: javascriptarrays

解决方案


您可以使用Array.prototype.find定位条目,然后简单地更新其id属性:

const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}];

const entry = arr.find(item => item.id === 'fifth');
entry.id = 'sixth';

console.log(arr);

您还可以使用Array.prototype.findIndex检索要替换的条目的索引,并相应地对其进行修改:

const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}];

const targetIndex = arr.findIndex(item => item.id === 'fifth');
arr[targetIndex].id = 'sixth';

console.log(arr);


但是,上面的两种方法只能帮助找到第一个匹配元素。如果数组中有多个 ID 为 的条目fifth,则最好使用迭代:

const arr = [{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'}];

arr.forEach(item => {
  if (item.id === 'fifth') {
    item.id = 'sixth';
  }
});

console.log(arr);


推荐阅读