如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,而我尝试访问它,它将返回false吗?还是抛出错误?
如何检查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
最简单的检查方法是
"key" in object
例如:
var obj = {
a: 1,
b: 2,
}
"a" in obj // true
"c" in obj // false
返回值为true表示键存在于对象中。
香草js
yourObjName.hasOwnProperty(key) : true ? false;
如果要检查对象在es2015中是否至少具有一个属性
Object.keys(yourObjName).length : true ? false
如果您使用的是underscore.js库,则对象/数组操作将变得简单。
在您的情况下,可以使用_.has方法。例:
yourArray = {age: "10"}
_.has(yourArray, "age")
返回true
但,
_.has(yourArray, "invalidKey")
返回假
"key" in obj
可能只测试与数组键有很大不同的对象属性值
该接受的答案是指对象。当心在数组上使用in
运算符查找数据而不是键:
("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
要测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?
New awesome solution with JavaScript Destructuring:
Do check other use of JavaScript Destructuring