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

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


当前回答

在我的例子中,我想检查LUIS返回的NLP元数据,它是一个对象。我想检查一个字符串“FinancialRiskIntent”的键是否作为元数据对象中的键存在。

我试图将需要检查的嵌套对象作为目标->data.meta.precision.intents(仅出于我自己的目的,您的对象可以是任何对象)我使用以下代码检查密钥是否存在:

const hasKey=data.meta.prprediction.intents中的“财务风险意图”;if(hasKey){console.log('密钥存在。');}其他{console.log('密钥不存在。');}

这是在检查我最初寻找的特定密钥。

希望这一点对某人有所帮助。

其他回答

答覆:

if ("key" in myObj)
{
    console.log("key exists!");
}
else
{
    console.log("key doesn't exist!");
}

说明:

in运算符将检查对象中是否存在密钥。如果检查值是否未定义:如果(myObj[“key”]==“undefined”),则可能会遇到问题,因为对象中可能存在具有未定义值的键。

出于这个原因,最好先使用in运算符,然后在知道键存在后比较键内的值。

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

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

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

But,

_.has(yourArray, "invalidKey")

返回false

接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?

如果在项目中配置了ESLint,则遵循ESLint规则,没有内置原型。以下链接描述了原因:

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));

香草js

yourObjName.hasOwnProperty(key) : true ? false;

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

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