Checking if a key exists in a JavaScript object?

前端 未结 22 2232
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

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?<

相关标签:
22条回答
  • 2020-11-21 23:28

    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.

    0 讨论(0)
  • 2020-11-21 23:28
    const object1 = {
      a: 'something',
      b: 'something',
      c: 'something'
    };
    
    const key = 's';
    
    // Object.keys(object1) will return array of the object keys ['a', 'b', 'c']
    
    Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';
    
    0 讨论(0)
  • 2020-11-21 23:29

    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
    }
    
    0 讨论(0)
  • 2020-11-21 23:29
    "key" in obj
    

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

    0 讨论(0)
  • 2020-11-21 23:29

    While this doesn't 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.

    0 讨论(0)
  • 2020-11-21 23:31

    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"]
    
    0 讨论(0)
提交回复
热议问题