如何检查JavaScript对象或数组中是否存在特定键?

如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?


当前回答

如果要检查对象上任何深度的任何键并考虑假值,请考虑实用函数的这一行:

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

后果

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

另请参阅此NPM包:https://www.npmjs.com/package/has-deep-value

其他回答

可选的Chaining(?.)运算符也可用于此

来源:MDN/Operators/Optional_chaining

常量冒险家={name:'爱丽丝',猫:{name:“Dinah”}}console.log(冒险家.dog?.name)//未定义console.log(冒险家.cat?.name)//Dinah

我们可以使用-hasOwnProperty.call(obj,key);

underscore.js方式-

if(_.has(this.options, 'login')){
  //key 'login' exists in this.options 
}

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};

如果您使用的是underscore.js库,那么对象/数组操作就变得简单了。

在您的情况下,可以使用_.has方法。例子:

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

But,

_.has(yourArray, "invalidKey")

返回false

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

香草js

yourObjName.hasOwnProperty(key) : true ? false;

如果要检查对象在es2015中是否至少有一个属性

Object.keys(yourObjName).length : true ? false