我从 laravel API 输出生成了一些新闻项目,我在一个 angular 4 cli 项目上显示这些项目。我注意到这些项目并没有按降序排列,我正试图在客户端解决这个问题。检查一下,这就是我得到的。
这是我从 api 得到的 JSON 输出:
{
"post": [
{
"id": 17,
"creator": null,
"title": "Test artikel 4",
"content": "<p>Dit is een test artikel voor het nieuws.</p>",
"tags": null,
"photo": "website/uploads/",
"sticky": 0,
"created_at": 1506000062,
"updated_at": false,
"category": ""
},
{
"id": 20,
"creator": null,
"title": "Test artikel 3",
"content": "<p>Dit is een test. Geen sticky.</p>",
"tags": null,
"photo": "website/uploads/",
"sticky": 0,
"created_at": 1506345662,
"updated_at": false,
"category": ""
},
{
"id": 23,
"creator": null,
"title": "Hovenier 2",
"content": null,
"tags": null,
"photo": "website/uploads/1505990708_Verboon Hoveniers.jpg",
"sticky": 0,
"created_at": 1506432062,
"updated_at": false,
"category": "Test categorie 1"
}
]
}
可以看到,数组中有一个基于unix时间戳的created_at对象。我要做的是使用 angular 4 typescript 根据 created_at 对象对这些项目进行排序。
我试过 sort() 函数,但我似乎无法让它工作。
谁能告诉我解决这个问题的最佳方法是什么?我认为它一定很简单,但我似乎无法理解。
谢谢!
编辑:我把它放在一个变量中,但我得到了这个: 错误类型错误:无法读取未定义的属性“排序”
此外,这是来自变量的 console.log。
最佳答案
也许这段代码可以帮助你:
const {posts} = yourJSON;
posts.sort((a, b) => a.created_at - b.created_at);
关于javascript - 以 Angular 从 API JSON 中排序的项目日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46541493/