An alternative to lodash.set when your object necessary working with immutable objects.
Installation
Using npm:
npm install --save setimmutable
In Node.js:
const set = ;
Mutable Vs. Immutable
In a simple object when do you use _.set
the data is updated if it is frozen nothing happens. The SetImmutable update the object tree until the final element to be replaced.
// const setLodash = require('lodash.set')// const setImmutable = require('setimmutable') // With mutable objectconst nextObjMutable = // Update the element and return the original object. nextObjMutable === originalObj // true // With immutable objectconst nextObjImmutable = // Update the tree element and return a new object. nextObjImmutable === originalObj // false
SetImmutable with complex constructors
To update the object tree is used the reference constructor. This makes a new object and assigns all old properties to the new object. But there are times when the constructor is complex and requires special properties to be declared.
// Simple Constructor { /* ... */ } // Complex Constructor { /* ... */ }
SetImmutable load the custom Clone to make a new object.
Example:
// const clone = require('setimmutable/clone') { }
API
set(object, path, value, [customClone])
Sets the value at path of object. If a portion of path doesn't exist, it's created.
Note: This not method mutates object. It re-create the object defined on the path.
Arguments
- object (Object): The object to modify.
- path (Array|string): The path of the property to set.
- value (*): The value to set.
- customClone: The function to customize clone object.
Returns
- ***(Object)***: Return object.
Example 1 (on RunKit)
const object = {} // => { '0': { '1': {'2': 'a' } } }
Example 2 (on RunKit)
const object = { } // => [ { 'people': [..., Person { 'firstName': 'Lucky' } ] } ]
Redux
SetImmutable withWith SetImmutable:
const set = { }
Without SetImmutable:
{ }