hasprop
Check if nested object has property
Last updated 6 years ago by miguelmota .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install hasprop 
SYNC missed versions from official npm registry.

hasprop

Check if nested object has property, the easy way.

Antiquated way:

var exists = Boolean(
  obj &&
  obj.qux &&
  obj.qux.zee &&
  obj.qux.zee.peep &&
  obj.qux.zee.peep[2] &&
  obj.qux.zee.peep[2].__data);

with hasProp:

var exists = hasProp(obj, ['qux', 'zee', 'peep', 2, '__data']);

Install

npm install hasprop

Usage

var hasProp = require('hasprop');

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)
hasProp(obj, ['foo']) // true
hasProp(obj, ['deedee']) // false
hasProp(obj, ['qux', 'zee', 'boop']) // true
hasProp(obj, ['qux', 'zee', 'peep', 0]) // true
hasProp(obj, ['qux', 'zee', 'peep', 1]) // true
hasProp(obj, ['qux', 'key.with.dots']) // true
hasProp(obj, ['qux', '"key.with.quotes"', 'greet']) // true
hasProp(obj, ['qux', 'zee', 'peep', 2]) // true
hasProp(obj, ['qux', 'zee', 'peep', 2, '__data']) // true
hasProp(obj, ['qux', '$el']) // true
hasProp(obj, ['foo.bar']) // true
hasProp(obj, ['qux', 'qux']) // false

// string for path
hasProp(obj, 'foo') // true
hasProp(obj, 'deedee') // false
hasProp(obj, 'qux.zee.boop') // true
hasProp(obj, 'qux.zee.peep.0') // true
hasProp(obj, 'qux.zee.peep.1') // true
hasProp(obj, 'qux.zee.peep[1]') // true
hasProp(obj, 'qux[key.with.dots]') // true
hasProp(obj, 'qux["key.with.quotes"].greet') // true
hasProp(obj, 'qux.zee.peep.2') // true
hasProp(obj, 'qux.zee.peep.2.__data') // true
hasProp(obj, 'qux.$el') // true
hasProp(obj, '[foo.bar]') // true
hasProp(obj, 'qux.qux') // false

Partially applied:

var objHasProp = hasProp(obj);

objHasProp(['foo']) //  true
objHasProp('[foo.bar']) // true
objHasProp(['qux']) // true
objHasProp(['yo']) // false

For getting the value, check out the module getprop.

License

MIT

Current Tags

  • 0.0.4                                ...           latest (6 years ago)

4 Versions

  • 0.0.4                                ...           6 years ago
  • 0.0.3                                ...           7 years ago
  • 0.0.2                                ...           7 years ago
  • 0.0.1                                ...           7 years ago
Maintainers (1)
Downloads
Today 4
This Week 4
This Month 5
Last Day 0
Last Week 0
Last Month 0
Dependencies (1)
Dev Dependencies (0)
None

Copyright 2014 - 2021 © npmmirror.com |