包详细信息

get-prop

miguelmota144.1kMIT0.0.10

Get a property from object

property, object

自述文件

getprop

Get a property from nested object, the easy way.

Antiquated way:

var value = 'default value';

if (
  obj &&
  obj.qux &&
  obj.qux.zee &&
  obj.qux.zee.peep &&
  obj.qux.zee.peep[2] &&
  obj.qux.zee.peep[2].__data) {

  value = obj.qux.zee.peep[2].__data;
}

with getProp:

var value = getProp(obj, ['qux', 'zee', 'peep', 2, '__data']);

Install

npm install get-prop
bower install getprop

Usage

var getProp = require('get-prop');

var obj = {
  foo: 'bar',
  qux: {
    zee: {
      boop: 4,
      peep: [55,'zonk', {
        __data: 'pow'
      }],
    },
    'key.with.dots': 'hello',
    '"key.with.quotes"': {
      greet: 'hi'
    },
    $el: 'element'
  },
  'foo.bar': 'noob',
  qax: null
};

// array for path (recommended)
getProp(obj, ['foo']) // 'bar'
getProp(obj, ['deedee']) // undefined
getProp(obj, ['deedee'], "I'm default value") // "I'm default value"
getProp(obj, ['qux', 'zee', 'boop']) // 'yo'
getProp(obj, ['qux', 'zee', 'peep', 0]) // 55
getProp(obj, ['qux', 'zee', 'peep', 1]) // 'zonk'
getProp(obj, ['qux', 'key.with.dots']) // 'hello'
getProp(obj, ['qux', '"key.with.quotes"', 'greet']) // 'hi'
getProp(obj, ['qux', 'zee', 'peep', 2]) // {__data: 'pow'}
getProp(obj, ['qux', 'zee', 'peep', 2, '__data']) // 'pow'
getProp(obj, ['qux', '$el']) // 'element'
getProp(obj, ['foo.bar']) // 'noob'
getProp(obj, ['qux', 'qux']) // undefined

// string for path
getProp(obj, 'foo') // 'bar'
getProp(obj, 'deedee') // undefined
getProp(obj, 'deedee', "I'm default value") // "I'm default value"
getProp(obj, 'qux.zee.boop') // 'yo'
getProp(obj, 'qux.zee.peep.0') // 55
getProp(obj, 'qux.zee.peep.1') // 'zonk'
getProp(obj, 'qux.zee.peep[1]') // 'zonk'
getProp(obj, 'qux[key.with.dots]') // 'hello'
getProp(obj, 'qux["key.with.quotes"].greet') // 'hi'
getProp(obj, 'qux.zee.peep.2') // {__data: 'pow'}
getProp(obj, 'qux.zee.peep.2.__data') // 'pow'
getProp(obj, 'qux.$el') // 'element'
getProp(obj, '[foo.bar]') // 'noob'
getProp(obj, 'qux.qux') // undefined

Partially applied:

var objProp = getProp(obj);

objProp(['foo']) //  'bar'
objProp('[foo.bar']) // 'noob'
objProp(['qux']) // 'noob'
objProp(['yo'], 'wut') // 'wut'

For a boolean version of this, check out the module hasprop.

License

MIT

更新日志

Change Log

All notable changes to this project will be documented in this file. This project adheres to Semantic Versioning.

[0.0.7] - 2015-06-17

Added

  • Partial application support.

[0.0.9] - 2016-01-04

Added

  • Array as path support.