utils-deep-get

1.0.0 • Public • Published

Deep Get

NPM version Build Status Coverage Status Dependencies

Deep get a nested property.

Installation

$ npm install utils-deep-get

For use in the browser, use browserify.

Usage

var deepGet = require( 'utils-deep-get' );

deepGet( obj, path[, options] )

Deep get a nested property.

var obj = { 'a': { 'b': { 'c': 'd' } } };
 
var val = deepGet( obj, 'a.b.c' );
// returns 'd'

For paths including arrays, specify the numeric index.

var arr = [
    { 'a': [ {'x': 5} ] },
    { 'a': [ {'x': 10} ] }
];
 
var val = deepGet( arr, '1.a.0.x' );
// returns 10

The key path may be specified as either a delimited string or a key array.

var obj = { 'a': { 'b': { 'c': 'd' } } };
 
var val = deepGet( obj, ['a','b','c'] );
// returns 'd'

The function accepts the following options:

  • sep: key path separator. Default: '.'.

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 val = deepGet( obj, 'a/b/c', {
    'sep': '/'
});
// returns 'd'

deepGet.factory( path[, options] )

Creates a reusable deep get factory. The factory method ensures a deepGet function is configured identically by using the same set of provided options.

var dget = deepGet.factory( 'a/b/c', {
    'sep': '/'
});

dget( obj )

Deep get a nested property.

var obj = { 'a': { 'b': { 'c': 'd' } } };
 
var val = dget( obj );
// returns 'd'

Examples

var deepGet = require( 'utils-deep-get' );
 
var data,
    keys,
    val,
    i;
 
data = new Array( 100 );
for ( i = 0; i < data.length; i++ ) {
    data[ i ] = {
        'x': Date.now(),
        'y': [ Math.random(), Math.random(), i ]
    };
}
 
keys = [ 0, 'y', 2 ];
for ( i = 0; i < data.length; i++ ) {
    keys[ 0 ] = i;
    val = deepGet( data, keys );
    console.log( val );
}

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

MIT license.

Copyright

Copyright © 2015. Athan Reines.

Package Sidebar

Install

npm i utils-deep-get

Weekly Downloads

382

Version

1.0.0

License

MIT

Last publish

Collaborators

  • kgryte