我有一个数组,其中包含javascript / typescript中的对象。
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]如何更新第二个元素的名称(使用id 2)并使用javascript (.)将数组复制到新数组接线员?
发布于 2017-06-13 14:33:44
您可以使用.map和 spread operator的混合
可以在创建新数组后设置值
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; }
https://stackoverflow.com/questions/44524121
复制相似问题