如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
虽然这不一定检查键是否存在,但它确实检查值的真实性。其中未定义和空值属于。
布尔(obj.foo)
这个解决方案最适合我,因为我使用了typescript,并且在obj或obj.hasOwnProperty('fo')中使用了像so'foo'这样的字符串检查密钥是否存在并不能为我提供智能感知。
其他回答
接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:
("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?
如果要检查对象上任何深度的任何键并考虑假值,请考虑实用函数的这一行:
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
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
检查JavaScript Destructuring的其他用法
答覆:
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