Object Attribute Path Traverser. Safely traverse the javascript attribute tree using a text path representation. You can also check the existence of the path.
For example, I didn't like to write the following code every time... humm...
const value = {
children: {
john: {hobby: [{name: "Cycling"}, {name: "Dance"}], pet: [{type: "dog", name: "Max"}]},
tom: {hobby: [{name: "Squash"}], pet: [{type: "cat", name: "Chloe"}]}
}
};
var answer = undefined;
if (value.children) {
if (value.children.john) {
if (value.children.john.hobby) {
if (Array.isArray(value.children.john.hobby)) {
if (value.children.john.hobby.length >= 2) {
if (value.children.john.hobby[1].name) {
answer = value.children.john.hobby[1].name;
}
}
}
}
}
}
The ugly thing above is nice if you can write it like this, right?
const {AttrPath}: any = require("attrpath");
var answer = AttrPath.traverse(value, ".children.john.hobby[1].name");
Safely traverse the object path using the given path string. Also, an array may be included in the middle of the path.
npm install atttrpath
const {AttrPath}: any = require("attrpath");
// or
import {AttrPath} from 'attrpath';
params
object: any Target Object.
path: string Traverse path. The beginning of the path is always ".".
e.g. ".cat.eye.left", ".dog['leg'][1].pad"
result: any Objects obtained as a result of traverse.
AttrPath.traverse(object: any, path: string): any;
params
path: string Traverse path.
result: boolean path is grammatically correct?
AttrPath.is_valid(path: string): boolean;
const {AttrPath}: any = require("attrpath");
const value = {
children: {
john: {
hobby: [{name: "Cycling"}, {name: "Dance"}],
pet: [{type: "dog", name: "Max"}]
},
tom: {
hobby: [{name: "Squash"}],
pet: [{type: "cat", name: "Chloe"}]
}
}
};
console.log(AttrPath.traverse(value, '.children.john.hobby[0].name'))
> "Max"
console.log(AttrPath.traverse(value, '.children.john.hobby[1].name'))
> undefined
console.log(AttrPath.is_valid('.children.john.hobby[0].name'))
> true
console.log(AttrPath.is_valid('.children.john.hobby[0]..name'))
> false
const value = {
children: {
john: {
hobby: [{name: "Cycling"}, {name: "Dance"}],
pet: [{type: "dog", name: "Max"}]
},
tom: {
hobby: [{name: "Squash"}],
pet: [{type: "cat", name: "Chloe"}]
}
}
};
import {AttrPath} from 'attrpath';
AttrPath.traverse(value, '.children')
AttrPath.is_valid('.children["john"].hobby[1].name')
const {AttrPath} = require('attrpath');
AttrPath.traverse(value, '.children');
AttrPath.is_valid('.children["john"].hobby[1].name')
See demo.md for unclear cases.
"AttrPath" is under MIT license.
Generated using TypeDoc