Skip to content

Examples

Vitaly Tomilov edited this page Mar 9, 2021 · 54 revisions

Examples for a few interesting special cases.

Accessing array elements

Array elements can be accessed via properties-indexes:

import {resolveValue} from 'path-value';

const obj = {
    data: ['first', {value: 'second'}]
};

resolveValue(obj, 'data.0'); //=> 'first'
resolveValue(obj, 'data.1.value'); //=> 'second'

// when path is an array, you can pass indexes as either strings or numbers:
resolveValue(obj, ['data', '0']); //=> 'first'
resolveValue(obj, ['data', 0]); //=> 'first'

resolveValue(obj, ['data', '1', 'value']); //=> 'second'
resolveValue(obj, ['data', 1, 'value']); //=> 'second'

JavaScript evaluates .0 syntax naturally, so it is very fast, while parsing [0] brings a performance penalty, plus ambiguities as to recognizing and handling invalid inputs. This library's focus is on simplicity and high performance.

Properties with dot in the name

To resolve a property that has a dot in its name, path has to be an array of property names:

import {resolveValue} from 'path-value';

const obj = {
    data : {
        'first.second': 123
    }
};

resolveValue(obj, ['data', 'first.second']); //=> 123

Alternatively, see Verbose Syntax.

Error on missing properties

When the last property does not exist, low-level function resolvePath sets exists: false flag in the returned descriptor.

Function resolveIfExists extends validation to throw a detailed error, if exists is false:

import {resolveIfExists} from 'path-value';

const obj = {
    first: {}
};

try {
        const value = resolveIfExists(obj, 'first.second');
} catch(e) {
    // e = PathExistError: Property "second" doesn't exist.
}

Verbose Syntax

All methods in this library work with a simple-syntax path only, to offer maximum value-resolution performance.

If however, you want to use full JavaScript syntax, then you will have to tokenize such path separately. Function tokenizePath supports full ES5 JavaScript syntax, and is separate from the rest, to avoid performance penalty from verbose path parsing.

import {resolveValue, tokenizePath} from 'path-value';

const path = tokenizePath(`first[2].second["text index"]`); // tokenizing verbose path
//=> ['first', '2', 'second', 'text index']

const target = {
    first: [0, 1, {second: {"text index": 123}}]
};

const value = resolveValue(target, path); //=> 123

Note that while tokenizePath supports complete ES5 JavaScript syntax, it only works correctly when the path is valid, because it does not do any syntax validation.