Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  75] [ 2]  / answers: 1 / hits: 74351  / 7 Years ago, tue, june 13, 2017, 12:00:00

I have an array containing objects in javascript / typescript.



let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]


How can I update name of the second element (with id 2) and copy the array to a new array using javascript spread (...) operator?


More From » typescript

 Answers
57

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; }





Or you can do it in the .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; }




[#57475] Saturday, June 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mathewb

Total Points: 535
Total Questions: 95
Total Answers: 96

Location: British Indian Ocean Territory
Member since Fri, Oct 15, 2021
3 Years ago
;