Javascript ES6/ES5 在数组中查找并更改 [英] Javascript ES6/ES5 find in array and change

查看:129
本文介绍了Javascript ES6/ES5 在数组中查找并更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组.我想按某个字段查找,然后更改它:

I have an array of objects. I want to find by some field, and then to change it:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundItem = items.find(x => x.id == item.id);
foundItem = item;

我希望它改变原始对象.如何?(我不在乎它是否也会在 lodash 中)

I want it to change the original object. How? (I dont care if it will be in lodash too)

推荐答案

您可以使用 findIndex 查找对象数组中的索引并根据需要替换:

You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

这假定 ID 是唯一的.如果您的 ID 重复(如您的示例中所示),则使用 forEach 可能会更好:

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});

这篇关于Javascript ES6/ES5 在数组中查找并更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆