get-valu
v1.3.2
Published
Get value from an object
Downloads
11
Maintainers
Readme
get-valu
Why you should consider using this project:
- VanillaJS
- no dependencies
- lightweight and fast
- supports all browsers and systems
- simplicity
- returns only 2 options: either
undefined
or desired value - second parameter (
path
) works as simple ascopy-paste
How to use
- Write the path to desired value:
a['b.c'][0].d.e
- Cut path:
['b.c'][0].d.e
- Paste as a second argument:
get(a, "['b.c'][0].d.e")
Install
Install with npm:
npm install get-valu
or with yarn:
yarn add get-valu
Usage
Supports object nesting
const get = require('get-valu');
const obj = { a: { b: { c: { d: 'e' } } } };
console.log(get(obj)); //=> { a: { b: { c: { d: 'e' } } } }
console.log(get(obj, 'a')); //=> { b: { c: { d: 'e' } } }
console.log(get(obj, 'a.b')); //=> { c: { d: 'e' } }
console.log(get(obj, 'a.b.c')); //=> { d: 'e' }
console.log(get(obj, 'a.b.c.d')); //=> 'e'
Supports complex keys with dots
console.log(get({ "a.b": "c" }, "['a.b']")); //=> 'c'
Supports array
console.log(get([{ a: "b" }], "[0]")); //=> { a: "b" }
console.log(get({ a: [{ b: "c" }] }, "a[0]")); //=> { b: "c" }
console.log(get({ a: [{ b: "c" }] }, "a[0].b")); //=> "c"
console.log(get({ a: { b: ["c"] } }, "a.b[0]")); //=> "c"
Supports functions
const a = () => {};
a.b = { c: "d" };
console.log(get(a, "")); //=> [Function a]
console.log(get(a, "b")); //=> { c: "d" }
console.log(get(a, "b.c")); //=> "d"
For more examples look unit tests.