如何检查对象内的动态属性的存在?
const result = {
"MEN": [],
"WOMEN": [],
"KIDS TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
const result = {
"MEN": [],
"WOMEN": [],
"CHILDREN TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
我有一个像上面这样的对象 result
。有时,它可能具有 KIDS TEMP
属性,有时可能具有 CHILDREN TEMP
。由于此属性有空格,我无法使用点运算符来获取这些属性。 如果 KIDS TEMP
或 CHILDREN TEMP
存在,我想创建一个标志。 我尝试了以下方法:-
const part = 'KIDS TEMP' || 'CHILDREN TEMP';
let check;
if (result) {
check = !!(result?.MEN.length !== 0 || result[part].length !== 0);
}
但是当我收到 CHILDREN TEMP
说它无法读取未定义的长度时,上面的代码就中断了。 我该如何解决这个问题?
const result = {
"MEN": [],
"WOMEN": [],
"KIDS TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
const result = {
"MEN": [],
"WOMEN": [],
"CHILDREN TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
I have an object result
like above. Sometimes, it may have KIDS TEMP
property and sometimes CHILDREN TEMP
. Since this property has spaces, I cannot use dot operator to fetch these properties.
I want to create a flag if either of KIDS TEMP
or CHILDREN TEMP
exist.
I tried below:-
const part = 'KIDS TEMP' || 'CHILDREN TEMP';
let check;
if (result) {
check = !!(result?.MEN.length !== 0 || result[part].length !== 0);
}
But the above code breaks when I receive CHILDREN TEMP
saying that it cannot read length of undefined.
How do I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Object.keys()
返回对象的属性名称。你可以这样检查一个对象是否拥有某个属性:如果你想测试某个属性是否存在,并且如果存在,则包含一个非空数组,你可以这样测试:
您的代码的主要问题是
const part = string1 || string2
始终计算为string1
,这不是您想要做的。Object.keys()
returns the property names of an object. You can check like this, if an object possesses a certain property:If you want to test, if a certain attribute exists, and in case it exists, contains a non-empty array, you can test it like this:
The main problem with your code is that
const part = string1 || string2
always evaluates tostring1
, which is not what you intend to do.您可以使用对象的方法 hasOwnProperty它将返回 true/false 取决于属性是否存在于对象中。
You can use Object's method hasOwnProperty it will return
true/false
depends on if property exists in object or not.