Checking if a key exists in a JavaScript object?

2018-12-31 04:04发布

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?

19条回答
旧人旧事旧时光
2楼-- · 2018-12-31 04:07

The easiest way to check is

"key" in object

for example:

var obj = {
  a: 1,
  b: 2,
}
"a" in obj // true
"c" in obj // false

Return value as true implies that key exists in the object.

查看更多
临风纵饮
3楼-- · 2018-12-31 04:10

Three ways to check if a property is present in a javascript object:

  1. !!obj.theProperty
    Will convert value to bool. returns TRUE for all but the 'false' value
  2. 'theProperty' in obj
    Will return true if the property exists, no matter its value (even empty)
  3. obj.hasOwnProperty('theProperty')
    Does not check the prototype chain. (since all objects have the 'toString' method, 1 and 2 will return true on it, while 3 can return false on it.)

Reference:

http://book.mixu.net/node/ch5.html

查看更多
荒废的爱情
4楼-- · 2018-12-31 04:14

For those which have lodash included in their project:
There is a lodash _.get method which tries to get "deep" keys:

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'
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


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.

查看更多
无与为乐者.
5楼-- · 2018-12-31 04:14

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

You should instead use the in operator:

"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark

查看更多
听够珍惜
6楼-- · 2018-12-31 04:15

These example can demonstrate the differences between defferent ways. Hope it will help you to pick the right one for your needs:

// Lets create object `a` using create function `A`
function A(){};
A.prototype.onProtDef=2;
A.prototype.onProtUndef=undefined;
var a=new A();
a.ownProp = 3;
a.ownPropUndef = undefined;

// Let's try different methods:

a.onProtDef; // 2
a.onProtUndef; // undefined
a.ownProp; // 3
a.ownPropUndef; // undefined
a.whatEver; // undefined
a.valueOf; // ƒ valueOf() { [native code] }

a.hasOwnProperty('onProtDef'); // false
a.hasOwnProperty('onProtUndef'); // false
a.hasOwnProperty('ownProp'); // true
a.hasOwnProperty('ownPropUndef'); // true
a.hasOwnProperty('whatEver'); // false
a.hasOwnProperty('valueOf'); // false

'onProtDef' in a; // true
'onProtUndef' in a; // true
'ownProp' in a; // true
'ownPropUndef' in a; // true
'whatEver' in a; // false
'valueOf' in a; // true (on the prototype chain - Object.valueOf)

Object.keys(a); // ["ownProp", "ownPropUndef"]
查看更多
情到深处是孤独
7楼-- · 2018-12-31 04:16

If you want to check for any key at any depth on an object and account for falsey values consider this line for a utility function:

var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;

Results

var obj = {
    test: "",
    locals: {
        test: "",
        test2: false,
        test3: NaN,
        test4: 0,
        test5: undefined,
        auth: {
            user: "hw"
        }
    }
}

keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
false
keyExistsOn(obj, "sdsdf.rtsd")
false
keyExistsOn(obj, "sdsdf.234d")
false
keyExistsOn(obj, "2134.sdsdf.234d")
false
keyExistsOn(obj, "locals")
true
keyExistsOn(obj, "locals.")
false
keyExistsOn(obj, "locals.auth")
true
keyExistsOn(obj, "locals.autht")
false
keyExistsOn(obj, "locals.auth.")
false
keyExistsOn(obj, "locals.auth.user")
true
keyExistsOn(obj, "locals.auth.userr")
false
keyExistsOn(obj, "locals.auth.user.")
false
keyExistsOn(obj, "locals.auth.user")
true

Also see this NPM package: https://www.npmjs.com/package/has-deep-value

查看更多
登录 后发表回答