Deep Set
Deep set a nested property.
Installation
$ npm install utils-deep-set
For use in the browser, use browserify.
Usage
var deepSet = ;
deepSet( obj, path, value[, options] )
Deep set a nested property.
var obj = 'a': 'b': 'c': 'd' ;var bool = ;/*{ 'a': { 'b': { 'c': 'beep' } } }*/
If the function is able to deep set a nested property, the function returns true
; otherwise, the function returns false
.
var bool = ;// returns truebool = ;// returns falsebool = ;// returns falsebool = ;// returns false
For paths
including arrays
, specify the numeric index.
var arr ='a': 'x': 5'a': 'x': 10;var bool = ;/*[{ 'a': [ {'x': 5} ] },{ 'a': [ {'x': 25} ] }]*/
The key path
may be specified as either a delimited string
or a key array
.
var obj = 'a': 'b': 'c': 'd' ;var bool = ;/*{ 'a': { 'b': { 'c': 'beep' } } }*/
If value
is a function
, the argument is treated as a callback
and should return a value to set.
{var ch = val;for var i = 0; i < 4; i++val += ch;return val;}var obj = 'a': 'b': 'c': 'd' ;var bool = ;/*{ 'a': { 'b': { 'c': 'ddddd' } } }*/
The function accepts the following options
:
- sep: key path separator. Default:
'.'
. - create:
boolean
indicating whether to create a path if the key path does not already exist. Default:false
.
By default, the function assumes dot
separated key values. To specify an alternative separator, set the sep
option.
var obj = 'a': 'b': 'c': 'd' ;var bool =;/*{ 'a': { 'b': { 'c': 'beep' } } }*/
To create a key path which does not already exist, set the create
option to true
.
var bool =;/*{'a': {'b': {'c': 'beep'},'e': {'c': 'boop'}}}*/
deepSet.factory( path[, options] )
Creates a reusable deep set factory. The factory method ensures a deepSet
function is configured identically by using the same set of provided options
.
var dset = deepSet;
dset( obj, value )
Deep sets a nested property.
var obj = 'a': 'b': 'c': 'd' ;var bool = ;/*{ 'a': { 'b': { 'c': 'beep' } } }*/
Examples
var deepSet = ;var databoolkeysi;{return val * 10;}data = 100 ;for i = 0; i < datalength; i++data i ='x': Date'y': Math Math i;keys = 0 'y' 2 ;for i = 0; i < datalength; i++keys 0 = i;bool = ;if !boolconsole;console;
To run the example code from the top-level application directory,
$ node ./examples/index.js
Tests
Unit
Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:
$ make test
All new feature development should have corresponding unit tests to validate correct functionality.
Test Coverage
This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:
$ make test-cov
Istanbul creates a ./reports/coverage
directory. To access an HTML version of the report,
$ make view-cov
License
Copyright
Copyright © 2015. Athan Reines.