检查键是否存在于JavaScript对象中?

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

如果密钥不存在,而我尝试访问它,它将返回false吗?还是抛出错误?

Tony猿2020/03/09 13:24:46

New awesome solution with JavaScript Destructuring:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

Do check other use of JavaScript Destructuring

村村小小十三2020/03/09 13:24:46

如果要检查对象上任何深度的任何键并考虑虚假值,请考虑将以下行用于实用程序功能:

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

Green达蒙2020/03/09 13:24:46

最简单的检查方法是

"key" in object

例如:

var obj = {
  a: 1,
  b: 2,
}
"a" in obj // true
"c" in obj // false

返回值为true表示键存在于对象中。

理查德西门Near2020/03/09 13:24:45

香草js

yourObjName.hasOwnProperty(key) : true ? false;

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

Object.keys(yourObjName).length : true ? false
古一斯丁猴子2020/03/09 13:24:45

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

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

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

但,

_.has(yourArray, "invalidKey")

返回

西里阳光2020/03/09 13:24:45
"key" in obj

可能只测试与数组键有很大不同的对象属性值

2020/03/09 13:24:45

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

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

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