How do I check if a particular key exists in a JavaScript object or array?
If a key doesn\'t exist, and I try to access it, will it return false? Or throw an error?<
lodash
included in their project:Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
var object = { 'a': [{ 'b': { 'c': 3 } }] };
console.log(
_.get(object, 'a[0].b.c'), // => 3
_.get(object, ['a', '0', 'b', 'c']), // => 3
_.get(object, 'a.b.c'), // => undefined
_.get(object, 'a.b.c', 'default') // => 'default'
)
This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.