我有一个包含javascript / typescript中对象的数组。
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]
如何更新第二个元素的名称(ID为2)并使用javascript spread(...)运算符将数组复制到新数组?
答案 0 :(得分:8)
您可以混合使用.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; }
答案 1 :(得分:1)
您可以在map
中这样做,不需要spread
:
const array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]
const updatedArray = array.map(a => {
if (a.id == 2) {
a.name = 'New Name';
}
return a;
});
答案 2 :(得分:0)
有几种方法可以做到这一点。我建议使用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返回一个新数组,因此您不需要数组扩展运算符。
答案 3 :(得分:0)
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let array2 =[...array.slice(0, 0), Object.assign({}, array[0], {
name:'new one' //change any property of idx
}),...array.slice(0 + 1)]
console.log(array);
console.log(array2);
[...array.slice(0, idx), Object.assign({}, array[idx], {
x:new_x //change any property of idx
}),...array.slice(idx + 1)]
答案 4 :(得分:0)
let array = [
{ id: 1, name: "One", location: { lat: 23.2223, lng: 56.2214 } },
{ id: 2, name: "Two", location: { lat: 23.2223, lng: 56.2214 } },
{ id: 3, name: "Three", location: { lat: 23.2223, lng: 56.2214 } },
];
我有这样的数组我该怎么办? 请告诉我,以上答案无法更改位置对象。
答案 5 :(得分:0)
我们可以使用
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let array2 = [...array]
array2.find(a => a.id == 2).name = "Not Two";
console.log(array2);
答案 6 :(得分:0)
您可以简单地使用map()
并在那里更改元素。
这是代码---
array_copy = array.map((element) => {
console.log(element.id);
if (element.id === 2) {
element.name = "name changed";
}
return element;
});
console.log(array_copy);
在这里,主数组也被修改,因为数组中的元素是对象,并且即使在新数组中也引用相同的位置。