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

查看:1715
本文介绍了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)

推荐答案

您可以使用

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天全站免登陆