Updating Copies Of Data in Javascript Without Changing Original Source

Updating Copies Of Data in Javascript Without Changing Original Source

Sometimes we need to mutate copies of data in javascript and working on it without altering the original source, so in this article we will take a look at two important npm packages to achieve this.

 

 

 

Javascript applications such as applications built on Reactjs or Vuejs needs a way to update state by making copy of it without altering the original source. If you with React or Vue before you will see that when you need to update state the only way is to copy the original state, then update and finally return the updated state.

To update state the classic way most people follow is using Object.assign() to copy the object and work on it.

consider this example:

Now we need to alter this object by modifying x to 5 we can use Object.assign():

This is a trivial example but consider this complex object:

Now if need to alter this object products second element, using Object.assign() is a tedious task. To overcome these situations we will use either of these packages immutability-helper or updeep

 

Immutability Helper

To install immutability-helper via npm

Usage

Simple Push

Nested collections

(Shallow) Merge

Removing an element from an array

Autovivification

Auto creation of new arrays and objects when needed

 

Full list of commands

  • {$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. Note: The items in the array are applied sequentially, so the order matters. The indices of the target may change during the operation.
  • {$set: any} replace the target entirely.
  • {$toggle: array of strings} toggles a list of boolean fields from the target object.
  • {$unset: array of strings} remove the list of keys in array from the target object.
  • {$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.
  • {$add: array of objects} add a value to a Map or Set. When adding to a Set you pass in an array of objects to add, when adding to a Map, you pass in [key, value] arrays like so: update(myMap, {$add: [['foo', 'bar'], ['baz', 'boo']]})
  • {$remove: array of strings} remove the list of keys in array from a Map or Set.

 

Udeep

To install udeep via npm:

udeep provides similar methods like immutability-helper.

Usage

Simple update

Multiple updates

Use a function

ES6 computed properties

For a full list of commands refer to udeep github page.

 

 

Share this: