使用传播运算符更新包含对象的数组 [英] Update Array containing objects using spread operator
本文介绍了使用传播运算符更新包含对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,其中包含javascript/打字稿中的对象.
I have an array containing objects in javascript / typescript.
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]
如何更新第二个元素的名称(ID为2),并使用JavaScript传播(...)运算符将数组复制到新数组?
How can I update name of the second element (with id 2) and copy the array to a new array using javascript spread (...) operator?
推荐答案
您可以混合使用 ...
传播算子
You can use a mix of .map
and the ...
spread operator
您可以在创建新数组后设置值
You can set the value after you've created your new array
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let array2 = array.map(a => {return {...a}})
array2.find(a => a.id == 2).name = "Not Two";
console.log(array);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
或者,您可以在 .map
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let array2 = array.map(a => {
var returnValue = {...a};
if (a.id == 2) {
returnValue.name = "Not Two";
}
return returnValue
})
console.log(array);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于使用传播运算符更新包含对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文