繁体   English   中英

如何检查 javascript 的 object(深度 4 级)数组中是否存在项目/元素

[英]How to check if an item/element exists in array of object ( depth 4 level ) in javascript

I am working on an angular application where I have loaded site settings from an API, this api returns a json object something like following

"data":{
  "merchant_settings": {
    "admin": {
      "def_referral_amount": 50,
      "card_payment_mode": "test",
      "min_amount": 150,
      "payment_mode": true
    },
    "bookings": {
      "allow_calendar_to_customer": {
        "enable": "yes",
        "layout": "month"
      },
    },
  },
}

在模板文件中,我根据返回的数据显示部分,例如如果allow_calendar_to_customer.enable == yes然后向客户显示日历。 如果我从 API 获取数据,这将正常工作,但有时该数据可能未保存在 db 中,因此不会作为响应返回。 为了处理这种情况,我添加了如下条件

if( typeof(data) !== 'undefined' && 
        typeof(data.merchant_settings) !== 'undefined' && 
        typeof(data.merchant_settings.bookings) !== 'undefined' && 
        typeof(data.merchant_settings.bookings.allow_calendar_to_customer) !== 'undefined' && 
typeof(data.merchant_settings.bookings.allow_calendar_to_customer.enable) !== 'undefined' && 
        data.merchant_settings.bookings.allow_calendar_to_customer.enable == yes){
              /* show required content */
} 

在这种情况下,我必须检查我认为不是一个好的解决方案的每一个父元素,但我也不确定处理这种情况的最佳方法是什么,我期待像下面这样的东西会起作用,但事实并非如此。

if( typeof(data.merchant_settings.bookings.allow_calendar_to_customer.enable) !== 'undefined' && data.merchant_settings.bookings.allow_calendar_to_customer.enable == yes){
      /* show required content */
    } 

有人可以建议我一种更好的方法来实现这些类型的条件,这样我就不必检查 object 中的所有属性了吗?

使用可选链接。

可选的链接运算符 (?.) 允许读取位于连接对象链深处的属性值,而无需明确验证链中的每个引用是否有效。 这?。 运算符的功能类似于。 链接运算符,除了如果引用为空(null 或未定义)时不会导致错误,表达式会短路并返回未定义的值。


它已经存在了很长时间,以至于每个非 IE 浏览器都可以使用它 - 请参见此处

如果您需要支持 1.4% 的使用 IE 的用户, 您可以使用undefined而不使用typeof方法,只需== ,这会稍微清理您的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM