Update an Object Using the Spread Operator

04-13-2021

There is a time in every programmers career when they need to update OR override a value or set of values in an object, for you that might be today. The Spread Operator introduced into the JavaScript language as part of the ECMAScript 6 (ES6) specification in 2015 is a powerful syntax. The spread operator allows us to operator on any iterable element including objects and arrays.

Extending an object would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
const myObj = {
name: "Brian",
profession: "Rockstar"
}

function newObj(){
return {
...myObj,
location: "The World"
}
}

console.log(newObj()); // { name: "Brian", profession: "Rockstar", location: "The World" }

Updating or overriding a value in an object might look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
const myObj = {
name: "Brian",
profession: "Rockstar"
}

function newObj(){
return {
...myObj,
profession: "Lion Tamer"
}
}

console.log(newObj()); // { name: "Brian", profession: "Lion Tamer" }

The ordering of the elements when defining a new element (object, array, etc.) is important. Duplicate values, i.e. Profession: "Lion Tamer", will be overriden if another value of a matching key name occurs after that value has been assigned.