propath
Access deep property-values, arrays and functions using a path. Written in TypeScript. Paths are parsed for performance.
Install
Node.js
npm install propath --save
Usage
; const obj = a: b: "f" c: "g" "h" 'i' `_k` ; // Parse pathconst ab = ; // Get valuelet value = ab; // value === "f" // Return undefined if path doesn't existconst alm12 = ;value = alm12; // typeof value === "undefined" // Return predictable value if path doesn't existconst ano0pOrHello = ;value = ano0pOrHello; // value === "Hello" // Set valueab;value = ab; // value === "l" // Has valuelet hasAB = ab; // hasAB === trueconst hasABC = ; // hasABC === false // Delete valueab; // returns true if ab was found and deletedhasAB = ab; // hasAB === false // Get value from arrayconst ac0 = ;value = ac0; // value === "g"value = ; // value === "h" // Set value on arrayac0;value = ac0; // value === "m" // Get value from functionconst ad = ;value = ad // value === "i" // Get value from parametrized functionconst param = 'n';value = ; // value === "n_k"// -> Parameters are provided in JSON syntax
How propath deals with inherited properties
Propath doesn't differentiate between inherited and own properties.
Full API + examples
Import propath
;
Parse property-path / instantiate propath
;
- Type V is the value type, the path is expected to return
- Type D is the value type of the default value
Default value parameter is optional.
Property-path syntax
Value access
abcde
Values access is done by property-names separated by dots .
.
Array index
ab5
Value access is done by index number in square brackets [
and ]
.
Function call
abab
Calling functions is done by parameters in round brackets (
and )
.
- Function calls cannot be nested, but can contain whitespace.
- Parameters must be in JSON syntax, strings must be double quoted with
"
API
pp<T, D>(path :string, defaultValue :D) :<instance>
If propath
is imported as the name pp
, it is called as a function with optional type parameters T
specifying the type returned by the path and D
specifying the type of the default value.
D
can be omitted whileT
is provided.- Neither
T
norD
must be provided. - If
T
is omitted, return-type of.get
will beany
. - Default value can be omitted.
.get(<obj>) :T|any|D|undefined
Traverses the path, returns the value found in <obj>
if the path can be traversed completely. If it cannot, the default value or undefined
is returned.
.set(<obj>, value) :boolean
Traverses the path, sets the value if the path can be traversed completely in <obj>
. If it cannot, false
is returned.
.has(<obj>) :boolean
Traverses the path, return true
if the path can be traversed completely in <obj>
. If it cannot, false
is returned.
.delete(<obj>) :boolean
Traverses the path, deletes the value and returns true
if the path can be traversed completely in <obj>
. If it cannot, false
is returned.