attrpath

AttrPath

Object Attribute Path Traverser. Safely traverse the javascript attribute tree using a text path representation. You can also check the existence of the path.

GitHub package.json version npm version npm type definitions GitHub 7thCode node.js.yml GitHub last commit

README DEMO in detail


Motivation

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");

Features

Safely traverse the object path using the given path string. Also, an array may be included in the middle of the path.

Installation

npm install atttrpath

Usage

API

const {AttrPath}: any = require("attrpath");
// or
import {AttrPath} from 'attrpath';

traverse value.

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;

path is valid?

params

    path: string  Traverse path.

result: boolean  path is grammatically correct? 
AttrPath.is_valid(path: string): boolean;

Exsample

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

Example Data

    const value = {
children: {
john: {
hobby: [{name: "Cycling"}, {name: "Dance"}],
pet: [{type: "dog", name: "Max"}]
},
tom: {
hobby: [{name: "Squash"}],
pet: [{type: "cat", name: "Chloe"}]
}
}
};

ESModule

import {AttrPath} from 'attrpath';

AttrPath.traverse(value, '.children')
AttrPath.is_valid('.children["john"].hobby[1].name')

CommonJS

const {AttrPath} = require('attrpath');

AttrPath.traverse(value, '.children');
AttrPath.is_valid('.children["john"].hobby[1].name')

Note

See demo.md for unclear cases.

Author

info@seventh-code.com

License

"AttrPath" is under MIT license.

Generated using TypeDoc