Immutably change Objects with Object.assign

May 29, 2017

Recently I’ve been working a lot with Redux. The library mandates immutability which means you have to find an immutable way to do every type of operation (remove an item from an array, change a value in an object, etc).

How to immutably change a value in an object

ES6 offers a cool method called Object.assign which lets you copy properties from one (or more) source objects to a target object. Let’s take a look at how it works!

const firstObject = {
  name: 'Object One',
  bar: () => { console.log('Hello world!')}
}

const secondObject = Object.assign(
  {},
  firstObject,
  {name: 'Object Two'}
)

console.log(secondObject) // Name will be "Object Two"

So the first parameter is an empty object (which is what will be returned with all the new properties). After that you can append as many object parameters as you want and just know the latest one will override. So for example:

const firstObject = {
  name: 'Object One',
  bar: () => { console.log('Hello world!')}
}

const secondObject = Object.assign(
  {},
  firstObject,
  {name: 'Object Two'},
  {name: 'Object Three'}
)

console.log(secondObject) // Name will be "Object Three"