JavaScript immutability-helper – Mutate a copy of data without changing the original source

Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like Clojure. However, we’ve provided a simple immutability helper, update(), that makes dealing with this type of data much easier, without fundamentally changing how your data is represented.

Say you have an object like so:

const user = {
  id: 787466,
  firstName: "Bramus",
  lastName: "Van Damme",
  messages: {
    12345678: {
      type: "text",
      content: "…",
      liked_by: [
         33296376,
         335658,
      ]
    },
    12345679: {
      type: "text",
      content: "…",
      liked_by: [
         558746,
         66314744,
      ]
    }
  }
}

Adding a new id onto one of the liked_by arrays in an immutable way is quite cumbersome, even when using a modern ES6 ES2015 syntax:

const newUser = {
  ...user,
  messages: {
    ...user.messages,
    12345679: {
      ...user.messages['12345679'],
      liked_by: [
        ...user.messages['12345679'].liked_by,
        589774125
      ]
    }
  }
}

YUCK!

Enter immutability-helper which allows us to write code like so:

import update from 'immutability-helper';

const newUser = update(user, {
  messages: {
    12345679: {
      liked_by: {
        $push: [589774125]
      },
    },
},
});

$push is the action to apply onto the source. Other actions provided by immutability-helper are:

  • {$push: array}: push() all the items in array on the target.
  • {$unshift: array}: unshift() all the items in array on the target.
  • {$splice: array of arrays}: for each item in arrays call splice() on the target with the parameters provided by the item.
  • {$set: any}: replace the target entirely.
  • {$merge: object}: merge the keys of object with the target.
  • {$apply: function}: passes in the current value to the function and updates it with the new returned value.

immutability-helper

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.