javascript - 从对象数组中查找和更改特定项目
问题描述
我正在处理一个像
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中做到这一点?
解决方案
您可以使用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);
推荐阅读
- oauth-2.0 - 如何使用用户 Api 密钥调用 youtube Api
- django - 如何在 Django/Mysql 中建立一对多关系?
- android - 我们是否开始在本地为 firebase 编写云函数?
- json - JSON格式spring boot的结果列表
- c# - 使用 WPF 和 MVVM 制作 NewGame 按钮
- java - 在从 servlet 过滤器输出消息后,如何从类中获取 JSP 输出消息?
- shell - awk:如何从查找文件中获取整个字符串
- python-3.x - 无法使用 xlsxwriter 附加 Excel 工作表
- python - 规范化/绘制文本数据,并在大型数据集上测试有效性
- asp.net - 使用 Blazor WebAssembly 的复合 UI