All articles
JavaScript ES6

Update an Object Using the Spread Operator

If you want to extend or override values in an object, using the spread operator in JavaScript can help

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:

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:

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.

Tagged

#JavaScript #ES6

Dealing with something harder than a blog post can fix?

Book a 30-minute call →