Use both method map and the spread operator to update objects in array JavaScript. set the value after you’ve created your new array.
Update object in array JavaScript using the spread operator
Simple example code updates the name of the second element (with id 2) and copies the array to a new array using the JavaScript spread (…) operator
<!DOCTYPE html>
<html>
<body>
<script>
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let res = array.map(a => {return {...a}})
res.find(a => a.id == 2).name = "Not Two";
console.log(res);
</script>
</body>
</html>
Output:
Or 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);
or with Object.assign
:
let new_array = array.map(element => element.id == 2 ? Object.assign({}, element, {name : 'New Name'}) : element);
Comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version