Checking if a key exists in a JavaScript object?

前端 未结 22 2235
礼貌的吻别
礼貌的吻别 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:46

    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 the 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 a 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 an 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 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[].
    

    Advice

    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) have changed the approach for access properties. The current implementation is slower than the previous one for this particular case but the difference between access key and object is neglectable.

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

    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.

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

    yourArray.indexOf(yourArrayKeyName) > -1

    fruit = ['apple', 'grapes', 'banana']
    
    fruit.indexOf('apple') > -1
    

    true


    fruit = ['apple', 'grapes', 'banana']
    
    fruit.indexOf('apple1') > -1
    

    false

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

    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'));

    0 讨论(0)
提交回复
热议问题