简体   繁体   English

如何从对象数组中获取最新数据

[英]How to get latest data from array of objects

I have an array of objects and each object has updatedDate . 我有an array of objects and each object has updatedDate I am trying get the latest UpdatedDateusing following lines of javascript but it returns NaN to me. 我正在尝试使用以下JavaScript行获取最新的UpdatedDateusing,但它将returns NaN给我。

var maxDate = Math.max.apply(Math, obj.reportsArray.map(function (o)
{
    return o.UpdatedDate;
}))

What i am doing wrong here? 我在这里做错了什么?

The problem is, that Math.max function requires type Numbers , and you are getting NaN when try to use it for different type of data. 问题是, Math.max函数需要类型Numbers ,而尝试将其用于不同类型的数据时会得到NaN

You need to convert the Date object to number, alike getTime() or similar function valueOf() , and if you need to get result at Date as well - then to convert Number back to Date . 您需要将Date对象转换为数字,就像getTime()或类似的函数valueOf() ,如果您还需要在Date处获取结果,则需要将Number转换回Date

var maxDate = Math.max.apply(Math, obj.reportsArray.map(function (o)
{
    return o.UpdatedDate.valueOf(); // <-- here you need the convertion of Date object
}))

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

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