get-lookup
JS helper for object deeply nested properties lookup. Much like
lodash.get
, but with some
additional useful features.
Installation
npm install --save get-lookup
Usage
Considering we have following object:
const obj = foo: bars: bak: 1 baz: 1 bak: 1 baz: 2 bak: 2 baz: 3 ;
Basic Usage
Path segments are delimitered by '.'
.
; ; // => 2
Property Lookup Keys
Probably the most useful feature of get-lookup
is ability to address objects
inside of arrays by their properties via lookup keys. In the example bellow we
use lookup key {bak:1}
, which resolves to the very first item in 'foo.bars'
array:
; // => 1
It is also possible to use several fields in property lookup keys to resolve ambiguity:
; // => 2
Note, however, that lookup keys should be used with simple values since they
uses ==
comparison.
Default Value
If the value resolved by get
function is undefined
, the default value, if
provided, is returned in its place:
const obj = foo: bar: 'baz'; ; // => 'bak';
Helpers
get-lookup
also exports a set of helper functions related to it's internal
logic, but that may come in handy sometimes:
;
isLookupKey(key)
- returnstrue
ifkey
represents a property lookup key.lookupIndex(array, key)
- returns an integer index of the element of the givenarray
that is identified by lookup keykey
. Returns-1
if no corresponding element is found.
Configuration
It is also possible to set custom value for lookup key term RegExp
. A term is
a part of the lookup key that represents property or value. Two terms together
with semicolon between them represent a segment. One or more segments separated
by commas and surrounded by curly braces represent lookup key itself.
To set custom term regular expression simply assign lookupTermRegExp
property
to get
function itself:
; ; // => false getlookupTermRegExp = /[\w\d@_-]+/; ; // => true
The default value for lookup key term regexp is /[\w\d_-]+/
.
License
MIT