如何在React中从JSON对象中查找最新的10个日期元素



我有一个包含日期元素的对象数组。我想从元素中找到最新的10个日期,并将它们呈现在表中。在每个datadata.date的映射中渲染,我得到了这个:

2020-12-12

2020-04-27

2020-08-26

2020-05-09

2020-09-08

2020-06-23

2020-02-28

2020-04-01

数据也具有不同的属性,如idcustomer_idcustomer_nameinvoices的数组。我想找到10个最新日期,并显示发票的客户名称,以及其他属性。

const findLatestDates = () => {
const sortedArray  = data.sort((a,b) => new Moment(a).format('YYYYMMDD') - new Moment(b).format('YYYYMMDD'))
return sortedArray;
};

我正在考虑按数组对日期进行排序,并循环15次以在渲染中显示它。这是个好主意吗?此外,new Moment上也出现了一个问题

目标缺少构造签名的"new"表达式隐式具有"any"类型。ts(7009(

使用Moment似乎有点过头了,我会尝试使用原生Date构造函数进行排序:

const findLatestDates = (data) => {
// Sort all data by date in a descending order
const sortedArray = data.sort(
(a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
);
// Get each data point corresponding to the most recent 10 days
const latestData = sortedArray.slice(0, 10);
return latestData;
};

如果在原始数据数组上运行此函数,则每个项应该仍然在一起,并且可以根据需要进行渲染。不需要对数据进行15次循环以获得所需的数据。

最新更新