Insides
Small JavaScript utility library for working with nested objects.
Installation
npm install insides --save
Quick Examples
var buildObject = buildObject; var reduceKV = reduceKV; var getIn = getIn; var setIn = setIn; var object = ; console; // { // "a": { // "b": { // "c": 1, // "d": 2 // } // }, // "e": 3 // } var depth = 3; var sum = ; console; // sum: 3 var abcValue = ; console; // abc value: 1 var abgValue = ; console; // abg value: not found var newObject = ; var newAbgValue = ; console; // new abg value: 10
Functions
buildObject(objectMap)
Creates object from nestedArray:
var object = ; // => { a: 2 } var object = ; // => { a: { b: 2 } } var object = ; // => { a: { b: 2, c: 3 } }
Argument is array of two-element arrays, first element is key map for the value, and second argument is the value;
getIn(object, keys, [notFound])
Returns value from nested object.
Arguments
object
- object from which to return valuekeys
- keys array, could be a string or a array of keys:"a"
,[ "a", "b" ]
or"a.b"
notFound
- optional not found value, defaults toundefined
Differences from object.a.b.c
:
If object.a
does not exists this will thor a TypeError
, getIn(object, [ "a", "b", "c" ])
returns undefined
.
setIn(object, keys, value/callback);
Sets value in object for provided keys array. Overwrites everything that was in this key and returns new object (initial one is left unchanged).
Arguments
object
- object to update valuekeys
- keys array, could be a string or a array of keys:"a"
,[ "a", "b" ]
or"a.b"
value/callback
- value or a callback to update the object:value
- overwrites object at given keys to provided valuecallback
- callscallback(key, value)
and replaces object at given key path to return value of the callback
updateIn(object, keys, value/callback);
The same as setIn
but updates the values instead of replacing them:
var object = "a": "b": 3 "c": 2 ; var setObject = ;// => { "a": { "b": 5 } } var updateObject = ;// => { "a": { "b": 5, "c": 2 } }
eachKV(object, [depth], callback)
Iterates over object calling callback on each matching value.
Arguments
object
- object to iterate on[depth]
- optional depth argument, positive integer, defaults to 0callback
- callback to be run on every matching node:callback(key, value, object)
mapKV(object, [depth], callback)
Same as eachKV
but returns new object instead of updating existing one, returns new object (initial one is left unchanged).
reduceKV(object, [depth], callback, [initialValue])
Reduces nested object using provided callback.
Arguments
object
- object to reduce[depth]
- optional depth argument, positive integer, defaults to 0callback
- callback to be run on every matching node:callback(memo, key, value, object)
[initialValue]
- optional initial value for firstmemo
incallback