object-path-immutable-yolo v0.5.1
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
npm install object-path-immutable --saveQuick 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)
const obj = {
a: {
b: 'c',
c: ['d', 'f']
}
}
const newObj = immutable.set(obj, 'a.b', 'f')
// {
// a: {
// b: 'f',
// c: ['d', 'f']
// }
// }
// obj !== newObj
// obj.a !== newObj.a
// obj.b !== newObj.b
// However:
// obj.c === newObj.cNote that you can also chain the api's and call value() at the end to retrieve the resulting object.
const newObj = immutable(obj).set('a.b', 'f').del('a.c.0').value()API
// Premises
const obj = {
a: {
b: 'c',
c: ['d', 'f']
}
}
import immutable from 'object-path-immutable'set (initialObject, path, value)
Changes an object property.
- Path can be either a string or an array.
- The value can be a function, allowing you to get the initial value of the property to do an update.
const newObj1 = immutable.set(obj, 'a.b', 'f')
const newObj2 = immutable.set(obj, ['a', 'b'], 'f')
const newObj3 = immutable.set(obj, ['a', 'b'], v => 'f')
// {
// a: {
// b: 'f',
// c: ['d', 'f']
// }
// }
// Note that if the path is specified as a string, numbers are automatically interpreted as array indexes.
const newObj = immutable.set(obj, 'a.c.1', 'fooo')
// {
// a: {
// b: 'f',
// c: ['d', 'fooo']
// }
// }push (initialObject, path, value)
Push into a deep array (it will create intermediate objects/arrays if necessary).
const newObj = immutable.push(obj, 'a.d', 'f')
// {
// a: {
// b: 'f',
// c: ['d', 'f'],
// d: ['f']
// }
// }delete (initialObject, path)
Deletes a property.
const newObj = immutable.del(obj, 'a.c')
// {
// a: {
// b: 'f'
// }
// }Can also delete a deep array item using splice
const newObj = immutable.del(obj, 'a.c.0')
// {
// a: {
// b: 'f',
// c: ['f']
// }
// }assign (initialObject, path, payload)
Shallow copy properties.
const newObj = immutable.assign(obj, 'a', { b: 'f', g: 'h' })
// {
// a: {
// b: 'f',
// c: ['d, 'f'],
// g: 'h'
// }
// }Equivalent library with side effects
Credits
- Mario Casciaro - Author
8 years ago