Checking if a key exists in a JavaScript object?

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

    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

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

    Here's a helper function I find quite useful

    This keyExists(key, search) can be used to easily lookup a key within objects or arrays!

    Just pass it the key you want to find, and search obj (the object or array) you want to find it in.

    function keyExists(key, search) {
            if (!search || (search.constructor !== Array && search.constructor !== Object)) {
                return false;
            }
            for (var i = 0; i < search.length; i++) {
                if (search[i] === key) {
                    return true;
                }
            }
            return key in search;
        }
    
    // How to use it:
    // Searching for keys in Arrays
    console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true
    console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false
    
    // Searching for keys in Objects
    console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true
    console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false

    It's been pretty reliable and works well cross-browser.

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

    We can use - hasOwnProperty.call(obj, key);

    The underscore.js way -

    if(_.has(this.options, 'login')){
      //key 'login' exists in this.options 
    }
    
    _.has = function(obj, key) {
      return hasOwnProperty.call(obj, key);
    };
    
    0 讨论(0)
  • 2020-11-21 23:43

    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

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

    a fast and easy solution is to convert your object to json then you will be able to do this easy task

        const allowed = {
            '/login' : '',
            '/register': '',
            '/resetpsw': ''
        };
        console.log('/login' in allowed); //returns true
    

    if you use an array the object key will be converted to integers ex 0,1,2,3 etc, therefore, it will always be false

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

    New awesome solution with JavaScript Destructuring:

    let obj = {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
    };
    
    let {key1, key2, key3, key4} = obj;
    
    // key1 = "value1"
    // key2 = "value2"
    // key3 = "value3"
    // key4 = undefined
    
    // Can easily use `if` here on key4
    if(!key4) { console.log("key not present"); } // Key not present
    

    Do check other use of JavaScript Destructuring

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