Get nested value inside a string, an array or an object.
- Server : Node.js >= 6.0.0
- Browser :
- Chrome >= 49
- Firefox >= 34
- Edge >= 12
- Opera >= 37
get(data, filter)
data
(string
||object
): Contains the datas to get.filter
(number
||object
||string
): Defines the content to get fromdata
. See the examples below.
If the filter
argument is a string
, it can contain the following operators in order to get nested object attributes.
a.b
: Get theb
attribute of the objecta
.a.*
: Get everything from the arraya
. Acts like amap()
function.a.*.b
: Map on the arraya
with theb
attribute.~a
: Keep the key/value data of the objecta
instead of only its value. This operator can only be placed before an object attribute.- e.g. : on
{ a: 1, b: 2 }
=> gets{ a: 1 }
instead of just1
.
- e.g. : on
const get = require('nested-get');
// Get from a string
get('foo', 1);
// => 'o'
get('foo', [0, 1]);
// => ['f', 'o']
// Get from an object
get({ a: 1, b: 1 }, 0);
// => { a: 1 }
get({ a: 1, b: 1 }, 'a');
// => 1
get({ a: 1, b: { c: 2 } }, 'b.c');
// => 2
get({ a: 1, b: { c: 2 } }, 'b.0');
// => { c: 2 }
get({ a: [1, 2, 3] }, 'a.1');
// => 2
get({ a: 1, b: 1 }, ['a', 0]);
// => [1, { a: 1 }]
// Get from an array
get([1, 2, 3], 1);
// => 2
get([1, 2, 3], [0, 1]);
// => [1, 2]
// '*' acts like a '.map()' function
get([{ a: 1, b: 2 }, { a: 3, b: 4 }], '*.a');
// => [1, 3]
get([{ a: 1, b: 2 }, { a: 3, b: 4 }], '*.0');
// => [{ a: 1 }, { a: 3 }]
get([{ a: 1, b: 2 }, { a: 3, b: 4 }], 'a'); // Works like '*.a' if applied to an array
// => [1, 3]
// '~' => Keeps the full object :
get([{ a: 1, b: 2 }, { a: 3, b: 4 }], '*.~a');
// => [{ a: 1 }, { a: 3 }]
MIT
Don't forget to 🌟 Star 🌟 the repo if you like this npm package !
Your feedback is appreciated