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:21

quick answer

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?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

The slow and reliable in operator and hasOwnProperty method

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

 var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

so, I tell you...

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

http://www.ecma-international.org/ecma-262/5.1/#sec-8.10

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each field’s name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

benchmark

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

Comparing key access in JS.

Using in operator
var result = "Impression" in array;

The result was

12,931,832 ±0.21% ops/sec      92% slower 
Using hasOwnProperty
var result = array.hasOwnProperty("Impression")

The result was

16,021,758 ±0.45% ops/sec     91% slower
Accessing elements directly (brackets style)
var result = array["Impression"] === undefined

The result was

168,270,439 ±0.13 ops/sec     0.02% slower 
Accessing elements directly (object style)
var result = array.Impression  === undefined;

The result was

168,303,172 ±0.20%     fastest

EDIT: What is the reason to assign to a property the undefined value?

That question puzzles me. In Javascript, there are at least two references for absent objects to avoid problems like this: null and undefined.

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

Compare:

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Advise

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

EDIT: 12/04/2018 - NOT RELEVANT ANYMORE

As people have commented, modern versions of the Javascript engines (with firefox exception) has changed the approach for access properties. Current implementation is slower than the previous one for this particular case but difference between access key and object are neglectable.

查看更多
裙下三千臣
3楼-- · 2018-12-31 04:21

It will return undefined.

var aa = {hello: "world"};
alert( aa["hello"] );      // popup box with "world"
alert( aa["goodbye"] );    // popup box with "undefined"

undefined is a special constant value. So you can say, e.g.

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}
查看更多
还给你的自由
4楼-- · 2018-12-31 04:22

While this necessarily check if a key exists, it does check for the truthiness of a value. Which undefined and null fall under.

Boolean(obj.foo)

This solution works best for me because I use typescript, and using strings like so 'foo' in obj or obj.hasOwnProperty('foo') to check whether a key exists or not does not provide me with intellisense.

查看更多
墨雨无痕
5楼-- · 2018-12-31 04:25
"key" in obj

Is likely testing only object attribute values that are very different from array keys

查看更多
一个人的天荒地老
6楼-- · 2018-12-31 04:27

Answer:

if ("key" in myObj)
{
    console.log("key exists!");
}
else
{
    console.log("key doesn't exist!");
}

Explanation:

The in operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined'), you could run into problems because a key could possibly exist in your object with the undefined value.

For that reason, it is much better practice to first use the in operator and then compare the value that is inside the key once you already know it exists.

查看更多
刘海飞了
7楼-- · 2018-12-31 04:28

ES6 solution

using Array#some and Object.keys. It will return true if given key exists in the object or false if it doesn't.

var obj = {foo: 'one', bar: 'two'};
    
function isKeyInObject(obj, key) {
    var res = Object.keys(obj).some(v => v == key);
    console.log(res);
}

isKeyInObject(obj, 'foo');
isKeyInObject(obj, 'something');

One-line example.

console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo'));

查看更多
登录 后发表回答