我在项目中使用AngularJS。
我从服务器获取对象数组。
每个对象都包含几个属性,其中之一是日期属性。
这是我从服务器获取的数组(json 格式):
[
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2019-02-01T00:01:01.001Z",
"MeasureValue": -1
},
{
"Address": 26,
"AlertType": 1,
"Area": "West",
"MeasureDate": "2016-04-12T15:13:11.733Z",
"MeasureValue": -1
},
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2017-02-01T00:01:01.001Z",
"MeasureValue": -1
}
.
.
.
]
我需要从数组中获取最新日期。
从对象数组中获取最新日期的优雅方法是什么?
一种干净的方法是将每个日期转换为Date()
并取最大值
ES6:
new Date(Math.max(...a.map(e => new Date(e.MeasureDate))));
JS:
new Date(Math.max.apply(null, a.map(function(e) {
return new Date(e.MeasureDate);
})));
where a
是对象数组。
其作用是将数组中的每个对象映射到使用以下值创建的日期MeasureDate
。然后将该映射数组应用于Math.max
函数获取最新日期并将结果转换为日期。
通过将字符串日期映射到 JS Date 对象,您最终会使用类似的解决方案数组中的最小/最大日期?
--
一个不太干净的解决方案是简单地将对象映射到MeasureDate
并对字符串数组进行排序。这仅适用于您使用的特定日期格式。
a.map(function(e) { return e.MeasureDate; }).sort().reverse()[0]
如果性能是一个问题,您可能需要reduce
数组来获取最大值而不是使用sort
and reverse
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)