更新对象数组中对象的属性
Update an Object’s Property in Array of Objects in JS
要更新对象数组中对象的属性,请使用该map()
方法遍历数组。在每次迭代中,检查当前对象是否是要更新的对象。如果是,则修改对象并返回结果,否则按原样返回对象。
// ✅ Updating properties in multiple objects const arr1 = [ {id: 1, name: 'Alice'}, {id: 1, name: 'Bob'}, {id: 3, name: 'Charlie'}, ]; const newArr = arr1.map(obj => { if (obj.id === 1) { return {...obj, name: 'Alfred'}; } return obj; }); // 👇️ [ // {id: 1, name: 'Alfred'}, {id: 1, name: 'Alfred'}, {id: 3, name: 'Charlie} // ] console.log(newArr);
我们传递给
Array.map
方法的函数被数组中的每个元素(对象)调用。
无论我们从传递给map()
方法的函数返回什么,都会插入到新数组中。
该map()
方法不会改变原始数组,它会返回一个新数组。
const arr1 = [ {id: 1, name: 'Alice'}, {id: 1, name: 'Bob'}, {id: 3, name: 'Charlie'}, ]; const newArr = arr1.map(obj => { if (obj.id === 1) { return {...obj, name: 'Alfred'}; } return obj; }); // 👇️ [ // {id: 1, name: 'Alfred'}, {id: 1, name: 'Alfred'}, {id: 3, name: 'Charlie} // ] console.log(newArr);
在每次迭代中,我们检查对象是否具有id
等于 的属性1
,如果是,我们使用
扩展运算符 (…)
解压缩对象的其他键值对,然后覆盖该name
属性。
如果不满足条件,我们将按原样返回对象。
2
objects with an id
of 1
. Since the map()
method iterates over the entire array, it updated both.This is inefficient if you only want to update the first property in the array
that matches a condition. In this scenario, you could use the
for…of
loop.
To update an object’s property in an array of objects, use the for...of
loop
to iterate over the array. On each iteration, check if the object is the one to
be updated and if it is, modify it and use the break
keyword to
short-circuit.
// ✅ Updating the property of a single Object const arr2 = [ {id: 1, name: 'Alice'}, {id: 1, name: 'Bob'}, {id: 3, name: 'Charlie'}, ]; for (const obj of arr2) { if (obj.id === 1) { obj.name = 'Alfred'; break; } } // 👇️ [{id: 1, name: 'Alfred'}, {id: 1, name: 'Bob'}, {id: 3, name: 'Charlie}] console.log(arr2);
The for...of
loop allows us to iterate over an array.
On each iteration, we check if the id
property of the object is equal to 1
.
If it is, we update the value of the name
property in the object and use the
break
keyword to exit the for
loop.
We only want to update the first object that matches the condition, so we
short-circuit to avoid unnecessary work.
Even though our array has 2
objects with an id
of 1
, only the name
property of the first object got updated.
map()
method, which returns a new array.