如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
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'));
其他回答
使用“反射”的替代方法
根据MDN
Reflect是一个内置对象,它提供可拦截的方法JavaScript操作。静态Reflect.has()方法的工作方式类似于in运算符作用
变量obj={a: 未定义,b: 1中,c: “hello world”}console.log(Reflect.has(obj,“a”))console.log(Reflect.has(obj,'b'))console.log(Reflect.has(obj,“c”))console.log(Reflect.has(obj,“d”))
我应该使用它吗?
这取决于。
Reflect.has()比公认答案中提到的其他方法慢(根据我的基准测试)。但是,如果您只在代码中使用它几次,我看不出这种方法有多大问题。
在我的例子中,我想检查LUIS返回的NLP元数据,它是一个对象。我想检查一个字符串“FinancialRiskIntent”的键是否作为元数据对象中的键存在。
我试图将需要检查的嵌套对象作为目标->data.meta.precision.intents(仅出于我自己的目的,您的对象可以是任何对象)我使用以下代码检查密钥是否存在:
const hasKey=data.meta.prprediction.intents中的“财务风险意图”;if(hasKey){console.log('密钥存在。');}其他{console.log('密钥不存在。');}
这是在检查我最初寻找的特定密钥。
希望这一点对某人有所帮助。
这些例子可以说明不同方式之间的差异。希望它能帮助您选择适合您需求的产品:
// 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"]
如果您使用的是underscore.js库,那么对象/数组操作就变得简单了。
在您的情况下,可以使用_.has方法。例子:
yourArray = {age: "10"}
_.has(yourArray, "age")
返回true
But,
_.has(yourArray, "invalidKey")
返回false
我们可以使用-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);
};