-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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.
The function takes the following arguments:
-
objectis a JavaScript value. In order to go inside, it should be either an object or a function. -
pathcan 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
delimiterand turned into an array path.
-
delimiteris 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.
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);