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.
Changelog
1.0
- Breaking change: The way the library handles empty paths has changed. Before this change,all the methods were returning the original object. The new behavior is as follows.
set(src, path, value)
: value
is returnedupdate(src, path, updater)
: value
will be passed to updater()
and the result returnedset(src, path, ...values)
: values
will be concatenated to src
if src
is an array, otherwise values
will be returnedinsert(src, path, value, at)
: if src
is an array then it will be cloned and value
will be inserted at at
, otherwise [value]
will be returneddel(src, path)
: returns undefined
assign(src, path, target)
: Target is assigned to a clone of src
and returned
Install
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
)
const obj = {
a: {
b: 'c',
c: ['d', 'f']
}
}
const newObj = immutable.set(obj, 'a.b', 'f')
Note 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
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.
const newObj1 = immutable.set(obj, 'a.b', 'f')
const newObj2 = immutable.set(obj, ['a', 'b'], 'f')
const newObj = immutable.set(obj, 'a.c.1', 'fooo')
update (initialObject, path, updater)
Updates an object property.
const obj = {
a: {
b: 1,
},
}
const newObj = immutable.update(obj, ['a', 'b'], v => v + 1)
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')
delete (initialObject, path)
Deletes a property.
const newObj = immutable.del(obj, 'a.c')
Can also delete a deep array item using splice
const newObj = immutable.del(obj, 'a.c.0')
assign (initialObject, path, payload)
Shallow copy properties.
const newObj = immutable.assign(obj, 'a', { b: 'f', g: 'h' })
insert (initialObject, path, payload, position)
Insert property at the specific array index.
const newObj = immutable.insert(obj, 'a.c', 'k', 1)
Equivalent library with side effects
object-path
Credits