0.5.6 • Published 12 months ago

attrpath v0.5.6

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

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 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;
                    }
                }
            }
        }
    }
}

or

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

No modules depend on it.


Usage

Import

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

traverse value.

result = AttrPath.traverse(object, path [default_value]);

params

paramsmeaning
object: anyTarget Object.
path: stringTraverse path. The beginning of the path is "." or "[".
e.g.".cat.eye.left", ".dog'leg'.pad" , etc...
default_value: anyThe value to return if there is no corresponding value in the object path. default is "undefined".
default_value: functionIf you give a function, give the traverse result to the first argument of the function.

result

resultmeaning
result: anyObjects obtained as a result of traverse.

Update the value if possible.

result = AttrPath.update(object, path , value);

params

paramsmeaning
object: anyTarget Object.
path: stringTraverse path. The beginning of the path is "." or "[".
e.g.".cat.eye.left", ".dog'leg'.pad" , etc...
value: anyThe value to update if the path exists.

result

resultmeaning
result: booleanHas an update.

path is grammatically valid?

result = AttrPath.is_valid(path);

params

paramsmeaning
path: stringTraverse path.

result

resultmeaning
result: booleanpath is grammatically correct?

Default Value

If the result is Undefined, the default value is returned.

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

    AttrPath.traverse({}, '.path', 1);

Example

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


const Default = (n:any) => {
	console.log(n);
}

AttrPath.traverse(value, '.children.john.hobby[0].name', Default)

> "Max"

console.log(AttrPath.is_valid('.children.john.hobby[0].name'))

> true

console.log(AttrPath.is_valid('.children.john.hobby[0]..name'))

> false

more Example

class Klass {
	member = "name";

	Member() {
		return AttrPath.traverse(this, '.member');
	}
}

const klass = new Klass();
console.log(klass.Member())

> "name"
class ParentKlass {
	member = "name";
}

class SubKlass extends ParentKlass {
	Member() {
		return AttrPath.traverse(this, '.member');
	}
}

const sub_klass = new SubKlass();
console.log(sub_klass.Member())

> "name"

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')

Array

The original value can be an array.

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

    AttrPath.traverse([1], '[0]');

Undefined

Returns Undefined if the original value is not an object.

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

    AttrPath.traverse(null, '.path');
    AttrPath.traverse(undefined, '.path');
    AttrPath.traverse(false, '.path');
    AttrPath.traverse(true, '.path');
    AttrPath.traverse(NaN, '.path');
    AttrPath.traverse(Infinity, '.path');
    AttrPath.traverse(0, '.path');
    AttrPath.traverse(-1, '.path');
    AttrPath.traverse("", '.path');
    AttrPath.traverse("1", '.path');
    AttrPath.traverse([1], '.path');
    AttrPath.traverse({}, '.path');

Tips

Note that the result object is just the argument object, so mutating the result object has the side effect of modifying the argument object. This side effect can actually be useful.

const before = [{name: "Dance"}];
AttrPath.traverse(before, '[0]').name = "Breaking";
console.log(before);
		
[{name: "Breaking"}]

Hostory

v0.5.5

update Method.

update Method impl.

v0.5.2

Bug Fix

Fixed to work correctly when the key contains ".".

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

    AttrPath.traverse(value, "['children.john']");

Note

The results of using objects, arrays, and symbols as keys are unknown.

See demo.md for unclear cases.

Author

info@seventh-code.com

License

"AttrPath" is under MIT license.

0.5.6

12 months ago

0.5.4

1 year ago

0.5.3

1 year ago

0.5.5

1 year ago

0.5.2

1 year ago

0.5.1

1 year ago

0.5.0

1 year ago

0.4.1

1 year ago

0.4.0

1 year ago

0.4.2

1 year ago

0.2.3

1 year ago

0.2.2

1 year ago

0.2.5

1 year ago

0.2.4

1 year ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago