javascript - 如何按嵌套数组中的日期对数组进行排序
问题描述
我有一组从 REST API 返回的对象。这些对象中的每一个也包含它自己的数组,如下所示:
{
"content": [
{
"id": 1,
"name": "Name 1",
"data": [
{
"id": "klqo1gnh",
"name": "Item 1",
"date": "2019-05-12"
}
]
},
{
"id": 2,
"name": "Name 2",
"data": [
{
"id": "klqo2fho",
"name": "Item 1",
"date": "2021-05-05"
},
{
"id": "klro8wip",
"name": "Item 2",
"date": "2012-05-05"
}
]
}
]
}
然后我映射数据,并返回它,就像这样(这是一个非常精简的例子):
{content.map((item) => {
return (
<div>
{item.name}
{item.date}
{item.id}
</div>
);
})}
就像你所期望的那样。然而,我需要做的是按日期排序,最好使用Moment.js
,在数组中找到包含最早日期的项目,然后首先显示该项目。例如, item"id": 2
包含 date 2012-05-05
,因为这是数据中最早的日期,所以我需要该 item 是第一个。我真的迷路了,Moment 的文档不是很清楚。
提前致谢。
解决方案
您可以使用 Moment.js 创建一个函数,该函数接受一个数组items
作为参数并返回一个按日期排序的新数组,可能是这样的:
function sortByDate(items: any[]) {
return items.sort((first, second) => {
if (moment(first.data.date).isSame(second.data.date)) {
return -1; // If they have the same date, return the first item
} else if (moment(first.data.date).isBefore(second.data.date)) {
return -1; // If the first date is earlier, return the first item
} else {
return 1; // The second date is earlier, so it goes first;
}
})
}
然后你可以在映射之前使用这个功能content
推荐阅读
- php - 如何在数据表中显示 2 张图像?
- android - 如何导入和使用 android x 库
- python - 类型提示一个变量与 Python 中的另一个变量具有相同的类型
- javascript - 如何每 x 分钟将 GPS 位置发送到 mysql 表
- python - 成功将十六进制编码为字节,但未能将字节转换回字符串-===>hex ->bytes;和字节->字符串
- c# - 如何从我的 WinForms 表单事件处理程序中操作类对象?
- javascript - 如何在 webpack 中为 png 正确配置加载器?
- python - 如何在 Odoo 9 的 qweb 模板的 t-field 中使用 OR 条件?
- javascript - Chrome 扩展 search_url 将 {searchTerm} 作为 post 参数值传递
- javascript - 是否可以将对象评估为布尔值?