如何检查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

其他回答

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

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

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

But,

_.has(yourArray, "invalidKey")

返回false

它将返回undefined。

var aa={hello:“world”};警报(aa[“hello”]);//带有“world”的弹出框警报(aa[“再见”]);//带有“未定义”的弹出框

undefined是一个特殊的常量值。所以你可以说,例如。

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

这可能是检查丢失钥匙的最佳方法。然而,正如下面的评论所指出的,理论上,您可能希望未定义实际值。我从来都不需要这样做,也无法马上想到我想要这样做的原因,但为了完整起见,您可以使用in运算符

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}
const rawObject = {};
rawObject.propertyKey = 'somethingValue';

console.log(rawObject.hasOwnProperty('somethingValue'));
// expected output: true

检查给定对象中存在的特定键,hasOwnProperty将在此处工作。

在我的例子中,我想检查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"]