【问题标题】:Accessing in array object javascript访问数组对象 javascript
【发布时间】:2018-05-27 05:35:19
【问题描述】:

有没有办法在 javascript 的一行代码中访问“inq”键的值?

[  
   {  
      "start_date":{  
         "gt":"2017-12-12 00:00:00"
      }
   },
   {  
      "start_date":{  
         "lt":"2017-12-13 23:59:59"
      }
   },
   {  
      "active":"true"
   },
   {  
      "city_ids":{  
         "inq":[  
            1006
         ]
      }
   }
]

我不想做 for 循环等等。 javascript 中简单的一行代码会很棒。 格式不固定,city_ids 可以是第一个、第二个或任何位置。

【问题讨论】:

  • foo[3].city_ids.inq[0] ?
  • 格式是固定的,还是可以改变的?
  • 格式不固定,city_ids可以排在第一位,也可以排在第二位。

标签: javascript arrays object search find


【解决方案1】:

您可以使用 array.prototype.find 来查找具有 city_ids 和 inq 属性的元素

var arr = [  
   {  
      "start_date":{  
         "gt":"2017-12-12 00:00:00"
      }
   },
   {  
      "start_date":{  
         "lt":"2017-12-13 23:59:59"
      }
   },
   {  
      "active":"true"
   },
   {  
      "city_ids":{  
         "inq":[  
            1006
         ]
      }
   }
];

var value = arr.find(e => e.city_ids && e.city_ids.inq)['city_ids']['inq'];
console.log(value);

【讨论】:

  • 0% 兼容 IE
  • 箭头函数的使用和Array.prototype.find()(顺便说一句)。
【解决方案2】:

解决办法

let data = [  
   {  
      "start_date":{  
         "gt":"2017-12-12 00:00:00"
      }
   },
   {  
      "start_date":{  
         "lt":"2017-12-13 23:59:59"
      }
   },
   {  
      "active":"true"
   },
   {  
      "city_ids":{  
         "inq":[  
            1006
         ]
      }
   }
]

console.log(data[3].city_ids.inq[0])

【讨论】:

    猜你喜欢
    • 2014-05-02
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2013-12-02
    • 2020-08-14
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多