我有一个数组,其中包含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; }
发布于 2017-06-13 14:40:16
有几种方法可以做到这一点。我建议使用Array.map:
let new_array = array.map(element => element.id == 2 ? {...element, name : 'New Name'} : element);或者使用Object.assign:
let new_array = array.map(element => element.id == 2 ? Object.assign({}, element, {name : 'New Name'}) : element);Map返回一个新数组,因此不需要数组扩展操作符。
发布于 2022-06-24 11:53:49
使用Spred运算符,可以使用以下方法更新特定的数组值
let array = [
{ id: 1, name: "One" },
{ id: 2, name: "Two" },
{ id: 3, name: "Three" },
];
const label = "name";
const newValue = "Two Updated";
// Errow comes if index was string, so make sure it was integer
const index = 1; // second element,
const updatedArray = [
...array.slice(0, index),
{
// here update data value
...array[index],
[label]: newValue,
},
...array.slice(index + 1),
];
console.log(updatedArray);
https://stackoverflow.com/questions/44524121
复制相似问题