0.1.5 • Published 4 years ago

keypaths v0.1.5

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

Keypaths

A tools for javascript Object key paths.

Install

npm install keypaths --save

Test

git clone https://github.com/hiowenluke/keypaths
cd keypaths
npm install
npm test

Usage

Convert the key paths of an object to an array

const kp = require('keypaths');

const obj = {
    a: {},
    b: {
        b1: {
            b11: {}
        },
        b2: {},
    },
    c: {},
};

const paths = kp.toPaths(obj);
console.log(paths);

Result

[
    'a',
    'b.b1.b11',
    'b.b2',
    'c',
]

Convert a key paths string array to an object

const kp = require('keypaths');

const paths = [
    'a',
    'b.b1.b11',
    'b.b2',
    'c',
];

const obj = kp.toObject(paths);
console.log(obj);

Result

{
    a: {},
    b: {
        b1: {
            b11: {}
        },
        b2: {},
    },
    c: {},
}

Get by key path

const kp = require('keypaths');

const obj = {
    a: {
        b: {
            c: 123
        }
    }
};

console.log(kp.get(obj, 'a.b.c')); // 123

Set by key path

const kp = require('keypaths');

const obj = {
    a: {
        b: {
            c: 123
        }
    }
};

kp.set(obj, 'a.b.c', [1, 2, 3]);
console.log(kp.get(obj, 'a.b.c')); // [1, 2, 3]

License

MIT

Copyright (c) 2019, Owen Luke