Skip to content

Library: getPath()

Eugene Lazutkin edited this page Jul 3, 2018 · 2 revisions

getPath() module is a function, which takes a path and an object then tries to dereference objects according to the path:

const object = {a: [true, {b: 1}, null]};

assert(getPath(object, 'a.1.b') === 1);
assert(getPath(object, 'a.0') === true);
assert(getPath(object, 'x.y') === undefined);

The idea is to read deep from an object safely without exceptions returning undefined when a path fails.

Usage

In a module-enabled environment (like Babel) it can be accessed like that:

import getPath from '@researchnow/reno/src/utils/getPath';

In global-based environments (like a browser) it is frequently mapped to Reno.utils.getPath.

getPath(object, path, delimiter='.')

The function takes the following arguments:

  • object is a JavaScript value. In order to go inside, it should be either an object or a function.
  • path can be one of two things:
    • An array of strings and/or numbers. In this case, each subsequent value will be used to dereference an object recursively.
    • A string. In this case, it will be split by delimiter and turned into an array path.
  • delimiter is a string or a regular expression object, which can be applied to a string path to turn it to an array.

It returns a final value or undefined if dereferencing failed at some point.

Examples

const object = {a: [true, {b: 1}, null]};

assert(getPath(object, 'a.1.b') === 1);
assert(getPath(object, ['a', 1, 'b') === 1);
assert(getPath(object, 'a/0', '/') === true);
assert(getPath(object, 'a=>5', '=>') === undefined);
assert(getPath(object, 'a, 1, b', /\s*,\s*/) === 1);

Clone this wiki locally