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

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


当前回答

这些例子可以说明不同方式之间的差异。希望它能帮助您选择适合您需求的产品:

// 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"]

其他回答

一个快速而简单的解决方案是将您的对象转换为json,然后您就可以完成这个简单的任务:

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

如果使用数组,则对象键将转换为整数(例如0,1,2,3等),因此,它将始终为false

检查javascript对象中是否存在属性的三种方法:

!!对象.属性将值转换为布尔值。对于除false值之外的所有值返回true对象中的“属性”如果属性存在,无论其值如何(甚至为空),都将返回trueobj.hasOwnProperty(“属性”)不检查原型链。(由于所有对象都有toString方法,因此1和2将返回true,而3可以返回false。)

参考:

http://book.mixu.net/node/ch5.html

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

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

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

ES6溶液

使用Array#some和Object.keys。如果给定的键存在于对象中,则返回true,否则返回false。

var obj={foo:'one',bar:'two'};函数isKeyInObject(obj,key){var res=对象.keys(obj).some(v=>v==key);console.log(res);}isKeyInObject(obj,'foo');isKeyInObject(obj,“something”);

单行示例。

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