Javascript ES6/ES5 在数组中查找并更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35206125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript ES6/ES5 find in array and change
提问by user3712353
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)
我希望它改变原始对象。如何?(我不在乎它是否也会在 lodash 中)
回答by CodingIntrigue
You can use findIndexto find the index in the array of the object and replace it as required:
您可以使用findIndex在对象的数组中查找索引并根据需要替换它:
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:
这假定唯一的 ID。如果您的 ID 重复(如您的示例中所示),则使用 forEach 可能会更好:
items.forEach((element, index) => {
if(element.id === item.id) {
items[index] = item;
}
});
回答by Soldeplata Saketos
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
:
如果您不想用新对象替换,而是要复制 的字段item
,则可以使用Object.assign
:
Object.assign(items[items.findIndex(el => el.id === item.id)], item)
Object.assign(items[items.findIndex(el => el.id === item.id)], item)
as an alternative with .map()
:
作为替代方案.map()
:
Object.assign(items, items.map(el=> el.id === item.id? item : el))
Object.assign(items, items.map(el=> el.id === item.id? item : el))
回答by Toodoo
An other approach is to use splice.
另一种方法是使用splice。
The
splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
N.B :In case you're working with reactive frameworks, it will update the "view", your array "knowing" you've updated it.
注意:如果您使用的是反应式框架,它会更新“视图”,您的数组“知道”您已经更新了它。
Answer :
回答 :
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
let foundIndex = items.findIndex(element => element.id === item.id)
items.splice(foundIndex, 1, item)
And in case you want to only change a value of an item, you can use findfunction :
如果您只想更改项目的值,则可以使用find函数:
// Retrieve item and assign ref to updatedItem
let updatedItem = items.find((element) => { return element.id === item.id })
// Modify object property
updatedItem.aProp = ds.aProp
回答by Fellow Stranger
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)
回答by katwal-Dipak
May be use Filter.
可以使用Filter。
const list = [{id:0}, {id:1}, {id:2}];
let listCopy = [...list];
let filteredDataSource = listCopy.filter((item) => {
if (item.id === 1) {
item.id = 12345;
}
return item;
});
console.log(filteredDataSource);
Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]
数组 [对象 { id: 0 }, 对象 { id: 12345 }, 对象 { id: 2 }]
回答by J?rgen
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 :)
尽管大多数现有答案都很棒,但我想包含一个使用传统 for 循环的答案,这里也应该考虑一下。OP 请求与 ES5/ES6 兼容的答案,并且传统的 for 循环适用:)
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.
在这种情况下使用数组函数的问题在于它们不会改变对象,但在这种情况下,需要改变。使用传统 for 循环的性能提升只是一个(巨大的)奖励。
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.
尽管我非常喜欢数组函数,但不要让它们成为您工具箱中的唯一工具。如果目的是改变数组,则它们不是最合适的。
回答by Daniel Laera
worked for me
为我工作
let returnPayments = [ ...this.payments ];
returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;
回答by tonymayoral
One-liner using spread operator.
使用扩展运算符的单行。
const updatedData = originalData.map(x => (x.id === id ? { ...x, updatedField: 1 } : x));