Javascript ES6/ES5 find in array and change

2020-05-11 03:30发布

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;

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

8条回答
手持菜刀,她持情操
2楼-- · 2020-05-11 03:38

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;

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;
    }
});
查看更多
We Are One
3楼-- · 2020-05-11 03:47

One-liner using spread operator.

 const updatedData = originalData.map(x => (x.id === id ? { ...x, updatedField: 1 } : x));
查看更多
相关推荐>>
4楼-- · 2020-05-11 03:48

Whereas most of the existing answers are great, I would like to include an answer using a traditional for loop, which should also be considered here. The OP requests an answer which is ES5/ES6 compatible, and the traditional for loop applies :)

The problem with using array functions in this scenario, is that they don't mutate objects, but in this case, mutation is a requirement. The performance gain of using a traditional for loop is just a (huge) bonus.

const findThis = 2;
const items = [{id:1, ...}, {id:2, ...}, {id:3, ...}];

for (let i = 0, l = items.length; i < l; ++i) {
  if (items[i].id === findThis) {
    items[i].iAmChanged = true;
    break;
  }
}

Although I am a great fan of array functions, don't let them be the only tool in your toolbox. If the purpose is mutating the array, they are not the best fit.

查看更多
再贱就再见
5楼-- · 2020-05-11 03:54

Given a changed object and an array:

const item = {...}
let items = [{id:2}, {id:3}, {id:4}];

Update the array with the new object by iterating over the array:

items = items.map(x => (x.id === item.id) ? item : x)
查看更多
Rolldiameter
6楼-- · 2020-05-11 03:54

worked for me

let returnPayments = [ ...this.payments ];

returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;
查看更多
萌系小妹纸
7楼-- · 2020-05-11 03:59

My best approach is:

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

items[items.findIndex(el => el.id === item.id)] = item;

Reference for findIndex

And in case you don't want to replace with new object, but instead to copy the fields of item, you can use Object.assign:

Object.assign(items[items.findIndex(el => el.id === item.id)], item)

as an alternative with .map():

Object.assign(items, items.map(el=> el.id === item.id? item : el))

查看更多
登录 后发表回答