Git Product home page Git Product logo

get-value's Introduction

get-value NPM version NPM monthly downloads NPM total downloads Linux Build Status

Use property paths like 'a.b.c' to get a nested value from an object. Even works when keys have dots in them (no other dot-prop library can do this!).

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Table of Contents

Details

Install

Install with npm:

$ npm install --save get-value

Usage

See the unit tests for many more examples.

const get = require('get-value');
const obj = { a: { b: { c: { d: 'foo' } } } };

console.log(get(obj));            //=> { a: { b: { c: { d: 'foo' } } } };
console.log(get(obj, 'a'));       //=> { b: { c: { d: 'foo' } } }
console.log(get(obj, 'a.b'));     //=> { c: { d: 'foo' } }
console.log(get(obj, 'a.b.c'));   //=> { d: 'foo' }
console.log(get(obj, 'a.b.c.d')); //=> 'foo'

Supports keys with dots

Unlike other dot-prop libraries, get-value works when keys have dots in them:

console.log(get({ 'a.b': { c: 'd' } }, 'a.b.c'));
//=> 'd'

console.log(get({ 'a.b': { c: { 'd.e': 'f' } } }, 'a.b.c.d.e'));
//=> 'f'

Supports arrays

console.log(get({ a: { b: { c: { d: 'foo' } } }, e: [{ f: 'g' }, { f: 'h' }] }, 'e.1.f'));   
//=> 'h'

console.log(get({ a: { b: [{ c: 'd' }] } }, 'a.b.0.c')); 
//=> 'd'

console.log(get({ a: { b: [{ c: 'd' }, { e: 'f' }] } }, 'a.b.1.e'));
//=> 'f'

Supports functions

function foo() {}
foo.bar = { baz: 'qux' };

console.log(get(foo));            
//=> { [Function: foo] bar: { baz: 'qux' } }

console.log(get(foo, 'bar'));     
//=> { baz: 'qux' }

console.log(get(foo, 'bar.baz')); 
//=> qux

Supports passing object path as an array

Slighly improve performance by passing an array of strings to use as object path segments (this is also useful when you need to dynamically build up the path segments):

console.log(get({ a: { b: 'c' } }, ['a', 'b']));
//=> 'c'

Options

options.default

Type: any

Default: undefined

The default value to return when get-value cannot resolve a value from the given object.

const obj = { foo: { a: { b: { c: { d: 'e' } } } } };
console.log(get(obj, 'foo.a.b.c.d', { default: true }));  //=> 'e'
console.log(get(obj, 'foo.bar.baz', { default: true }));  //=> true
console.log(get(obj, 'foo.bar.baz', { default: false })); //=> false
console.log(get(obj, 'foo.bar.baz', { default: null }));  //=> null

// you can also pass the default value as the last argument
// (this is necessary if the default value is an object)
console.log(get(obj, 'foo.a.b.c.d', true));  //=> 'e'
console.log(get(obj, 'foo.bar.baz', true));  //=> true
console.log(get(obj, 'foo.bar.baz', false)); //=> false
console.log(get(obj, 'foo.bar.baz', null));  //=> null

options.isValid

Type: function

Default: true

If defined, this function is called on each resolved value. Useful if you want to do .hasOwnProperty or Object.prototype.propertyIsEnumerable.

const isEnumerable = Object.prototype.propertyIsEnumerable;
const options = {
  isValid: (key, obj) => isEnumerable.call(obj, key)
};

const obj = {};
Object.defineProperty(obj, 'foo', { value: 'bar', enumerable: false });

console.log(get(obj, 'foo', options));           //=> undefined
console.log(get({}, 'hasOwnProperty', options)); //=> undefined
console.log(get({}, 'constructor', options));    //=> undefined

// without "isValid" check
console.log(get(obj, 'foo', options));           //=> bar
console.log(get({}, 'hasOwnProperty', options)); //=> [Function: hasOwnProperty]
console.log(get({}, 'constructor', options));    //=> [Function: Object]

options.split

Type: function

Default: String.split()

Custom function to use for splitting the string into object path segments.

const obj = { 'a.b': { c: { d: 'e' } } };

// example of using a string to split the object path
const options = { split: path => path.split('/') };
console.log(get(obj, 'a.b/c/d', options)); //=> 'e'

// example of using a regex to split the object path
// (removing escaped dots is unnecessary, this is just an example)
const options = { split: path => path.split(/\\?\./) };
console.log(get(obj, 'a\\.b.c.d', options)); //=> 'e'

options.separator

Type: string|regex

Default: .

The separator to use for spliting the string (this is probably not needed when options.split is used).

const obj = { 'a.b': { c: { d: 'e' } } };

console.log(get(obj, 'a.b/c/d', { separator: '/' }));       
//=> 'e'

console.log(get(obj, 'a\\.b.c.d', { separator: /\\?\./ })); 
//=> 'e'

options.join

Type: function

Default: Array.join()

Customize how the object path is created when iterating over path segments.

const obj = { 'a/b': { c: { d: 'e' } } };
const options = {
  // when segs === ['a', 'b'] use a "/" to join, otherwise use a "."
  join: segs => segs.join(segs[0] === 'a' ? '/' : '.')
};

console.log(get(obj, 'a.b.c.d', options));
//=> 'e'

options.joinChar

Type: string

Default: .

The character to use when re-joining the string to check for keys with dots in them (this is probably not needed when options.join is used). This can be a different value than the separator, since the separator can be a string or regex.

const target = { 'a-b': { c: { d: 'e' } } };
const options = { joinChar: '-' };
console.log(get(target, 'a.b.c.d', options)); 
//=> 'e'

Benchmarks

(benchmarks were run on a MacBook Pro 2.5 GHz Intel Core i7, 16 GB 1600 MHz DDR3).

get-value is more reliable and has more features than dot-prop, without sacrificing performance.

# deep (175 bytes)
  dot-prop x 883,166 ops/sec ±0.93% (86 runs sampled)
  get-value x 1,448,928 ops/sec ±1.53% (87 runs sampled)
  getobject x 213,797 ops/sec ±0.85% (90 runs sampled)
  object-path x 184,347 ops/sec ±2.48% (85 runs sampled)

  fastest is get-value (by 339% avg)

# root (210 bytes)
  dot-prop x 3,905,828 ops/sec ±1.36% (87 runs sampled)
  get-value x 16,391,934 ops/sec ±1.43% (83 runs sampled)
  getobject x 1,200,021 ops/sec ±1.81% (88 runs sampled)
  object-path x 2,788,494 ops/sec ±1.81% (86 runs sampled)

  fastest is get-value (by 623% avg)

# shallow (84 bytes)
  dot-prop x 2,553,558 ops/sec ±0.89% (89 runs sampled)
  get-value x 3,070,159 ops/sec ±0.88% (90 runs sampled)
  getobject x 726,670 ops/sec ±0.81% (86 runs sampled)
  object-path x 922,351 ops/sec ±2.05% (86 runs sampled)

  fastest is get-value (by 219% avg)

Running the benchmarks

Clone this library into a local directory:

$ git clone https://github.com/jonschlinkert/get-value.git

Then install devDependencies and run benchmarks:

$ npm install && node benchmark

Release history

v3.0.0

  • Improved support for escaping. It's no longer necessary to use backslashes to escape keys.
  • Adds options.default for defining a default value to return when no value is resolved.
  • Adds options.isValid to allow the user to check the object after each iteration.
  • Adds options.separator for customizing character to split on.
  • Adds options.split for customizing how the object path is split.
  • Adds options.join for customizing how the object path is joined when iterating over path segments.
  • Adds options.joinChar for customizing the join character.

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

Contributors

Commits Contributor
87 jonschlinkert
2 ianwalter
1 doowb

Author

Jon Schlinkert

License

Copyright © 2018, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on November 17, 2018.

get-value's People

Contributors

doowb avatar felladrin avatar jonschlinkert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

get-value's Issues

default value is useless without isValid call, which defaults to true for everything

Hi, I've noticed that defaultValue in the case like this:

get(options, 'property', false) would always return the value of property and would never return false

was this intentional to make isValid always return true? I cant imagine a case where one would want to define a default value and then never be able to get it with the current isValid implementation

Sorry for the remark if that was done by design, but if not - I imagine it would be great to update the lib

collection not accessible

cannot access property of object array.

var get = require('get-value');
get({a:['a','aa','aaa']}, 'a.2');
// => 'aaa'
get({c:[{},{b:1},{}]}, 'c.1');
// => { b: 1 }
get({c:[{},{b:1},{}]}, 'c.1.b');
// => undefined

Benchmark against object-path

A similar package to get-value is object-path, which has 2,163,767 downloads in the last month.

I think it's worth adding this package to the benchmark alongside dot-prop.

What do you think?

update dep

This is unfortunately... 2 diffrent major version of isObject is being used...

image

Could you update all dependencies?

Unexpected Identifier and WebpackJsonp not defined on building Android in Ionic

First of all i want to thank you for all those helpful contributions.

To the problem:
We are developing apps with ionic latest versions. If we try to build the android version we always get error in console caused by get-value 3.0.1. Unexpected Identifier (vendor.js) which causes WebpackJsonp to be undefined.

We switched back to get-value 2.0.6 and the error is gone.

Not sure how it comes, just wanted to let someone know about this problem.

Kindly regards,
Miro Krenz

Open to PR with `get(...default='default')`?

Same behavior as get(), but returns the default value instead of undefined?

For example...

> var obj = {a: {b: 'c'}}

> get(obj, 'a.b')
'c'

> get(obj, 'a.b.c.d.e')
undefined

> get(obj, 'a.b.c.d.e', default='default')
'default'

benckmark compare with object.get

How much difference in performance will be affected?

const Benchmark = require('benchmark');
const get = require('get-value');

const suite = new Benchmark.Suite;
const obj = { a: { b: { c: { d: 'foo' } } } };
get(obj, 'a.b.c.d')

suite
    .add('get-value#get', function () {
        get(obj, 'a.b.c.d');
    })
    .add('Object#get', function () {
        obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d;
    })
    .on('cycle', function (event) {
        console.log(String(event.target));
    })
    .on('complete', function () {
        console.log('Fastest is ' + this.filter('fastest').map('name'));
    })
    .run({ 'async': true });

get-value#get x 3,236,388 ops/sec ±1.14% (83 runs sampled)
Object#get x 75,850,967 ops/sec ±1.49% (87 runs sampled)

Performance gap: 75850967 / 3236388 =23.4 times

how to get a path of a key?

how to get a path of a key?
not the value.

I'm iterating all object keys, and store some important keys in another object, since my loop is in an important key, i want to store it, but how can i convert to a path?

const obj = {
   foo: {
      bar: true
   }
}

i want to return 'foo.bar'

Support for circular references?

Hello. Thank you for writing these modules, I was previously using dot-path, but am unable to since it moved to ESM.

One thing I've noticed about get-value is that it doesn't support circular references. The following two examples result in undefined

const get = require('get-value')
const a = {};
a.b = a;
get(a, 'a.b'); // undefined
const get = require('get-value')
const a = { c: 1 };
a.b = a;
get(a, 'a.b.c')  // undefined

Was this intentional?

Using array notation breaks when values has periods

Converting an array to a string by naive join results in periods that were previously in a key becoming two keys.

It'd be nicer if array notation was just passed through ad-hoc, and instead the string syntax is converted to array notation - the current method is kind of jank, array to string back to array with changes each step.

Issue with Default Value of 0

const obj = { a: {b: 3} };
const value = get(obj, 'a.b', {default: 0)); // value equals -> undefined
const value = get(obj, 'a.b', 0); // value equals -> 3

benchmark optional chaining

Would like to see how this is compared to native optional chaining in performances.

Maybe would like to see some comment in the readme that suggest optional chaining if possible

Support array notation in property path

The doc said it is supported but actually not.
It is not covered in test.

const get = require('get-value');
const obj = { e: [ {f : 'g'} ] };
console.log(get(obj, 'e[0].f')); // undefined
console.log(get(obj, 'e.0.f')); // 'g'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.