检查嵌套对象中是否存在对象成员
有没有比使用 ___ in object
检查对象的每个级别是否存在来检查单个成员是否存在更简单的方法?
更简洁:如何检查 someObject.member.member.member.value 是否存在?
Is there a simpler way than using ___ in object
to check the existence of each level of an object to check the existence of a single member?
More concisely: How can I check if someObject.member.member.member.value exists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
一般来说,您可以使用if(object中的property),但这对于嵌套成员来说仍然很麻烦。
您可以编写一个函数:
DEMO
In general, you can use
if(property in object)
, but this would be still cumbersome for nested members.You could write a function:
DEMO
您还可以尝试/捕获 TypeError?
You could also try/catch TypeError?
这是一种方法: http://jsfiddle.net/9McHq/
Here's one way: http://jsfiddle.net/9McHq/
查看 lodash-deep 的
deepHas
https://github.com/ marklagendijk/lodash-deep#_deephascollection-propertypath这也是https://github.com/danielstjules/hoops
Check out lodash-deep’s
deepHas
https://github.com/marklagendijk/lodash-deep#_deephascollection-propertypathAnd this too https://github.com/danielstjules/hoops
或类似:
如果任何特定值恰好为
null
、false
、0
或""< /code> (空字符串),但除了最终值可能存在的例外之外,情况似乎不太可能如此。
另请注意,
typeof ____ !== "undefined"
并不是判断对象是否具有属性的正确测试。相反,您应该使用___ in object
,例如if ("member" in someObject)
。这是因为您可以将属性设置为显式值undefined
,这与使用delete someObject.member
删除它不同。or similarly:
This will not 'work' if any particular value happens to be
null
,false
,0
, or""
(an empty string), but with the possible exception of the final value, this seems unlikely to be the case.Also, note that
typeof ____ !== "undefined"
is not the correct test to see if an object has a property. Instead you should use___ in object
, e.g.if ("member" in someObject)
. This is because you can set a property to an explicit value ofundefined
, which is different from removing it withdelete someObject.member
.类似于(警告:前面未经测试的代码)
Something like (warning: untested code ahead)
在 thecodeabode 上定义了一个 safeRead 函数允许安全读取嵌套属性
即,
如果任何属性为空或未定义,则返回空白字符串 - 对于格式化/字符串插值很有用
Theres a safeRead function defined here on thecodeabode which allows a safeRead of nested properties
i.e.
if any of the properties are null or undefined a blank string is returned - useful for formatting / string interpolation
如果您可以使用
lodash
库,它有一个非常优雅的解决方案,hasIn。例如,
If you can use
lodash
library, it has a very elegant solution, hasIn.for example,