A TypeScript function that resolves a string path to an object's property.
npm install resolve-object-path
npm install resolve-object-path --save
`
$3
`html
`
Importing
$3
`typescript
const resolvePath = require('resolve-object-path');
// or
import resolvePath from 'resolve-object-path';
`
$3
All declarations are automatically available in all other files.
Documentation
This package exports only one function, as the default export.
`typescript
resolvePath(object: object, path: string);
`
Where:
* object is the object to get the value from
* path is the path to the value
It returns the value the path was pointing to, or undefined if the object does not contain that path.
$3
* Throws if type of the argument object is not "object".
* Throws if type of the argument path is not "string".
* Throws if the path is invalid, such as "." or "v|as.t".
$3
`typescript
import resolvePath from 'reolve-object-path';
const testObj = {
foo: 'abc',
'tes"t': 'pizza',
'bra[ck"][et': 'cheese',
bar: {
baz: -5,
'str-ing': { prop: 86 },
'qux': [{}, { def: 'ghi' }],
'fred': [1, 3, 5],
}
};
resolvePath(testObj, ''); // returns the whole object
resolvePath(testObj, 'foo'); // -> "abc"
resolvePath(testObj, 'bar.baz'); // -> -5
resolvePath(testObj, 'bar.fred[2]'); // -> 5
resolvePath(testObj, '["foo"]'); // -> "abc"
resolvePath(testObj, '["foo"].bar'); // -> -5
resolvePath(testObj, 'bar["str-ing"]'); // -> { prop: 86 }
resolvePath(testObj, 'bar.qux[1].def'); // -> "ghi"
// even works in edge cases such as
resolvePath(testObj, '["tes"t"]'); // -> "pizza"
resolvePath(testObj, '["bra[ck"][et"]'); // -> "cheese"
``