object-path-immutable
Tiny JS library to modify deep object properties without modifying the original object (immutability).
Works great with React (especially when using setState()
) and Redux (inside a reducer).
This can be seen as a simpler and more intuitive alternative to the React Immutability Helpers and Immutable.js
Install
Node.js
npm install object-path-immutable --save
Quick usage
The following, sets a property without modifying the original object.
It will minimize the number of clones down the line. The resulting object is just a plain JS object literal,
so be warned that it will not be protected against property mutations (like Immutable.js
)
var obj = {
a: {
b: 'c',
c: ['d', 'f']
}
}
var newObj = immutable.set(obj, 'a.b', 'f')
API
var obj = {
a: {
b: 'c',
c: ['d', 'f']
}
}
var immutable = require("object-path-immutable")
var newObj = immutable.set(obj, 'a.b', 'f')
var newObj = immutable.set(obj, ['a', 'b'], 'f')
var newObj = immutable.set(obj, 'a.c.1', 'fooo')
var newObj = immutable.push(obj, 'a.d', 'f')
var newObj = immutable.del(obj, 'a.c')
var newObj = immutable.del(obj, 'a.c.0')
var newObj = immutable.assign(obj, 'a', { b: 'f', g: 'h' })
var newObj = immutable(obj).set(obj, 'a.b', 'f').del(obj, 'a.c.0').value()
Equivalent library with side effects
object-path
Credits