在底部,有一些关于我是如何来到这里的解释。在 ES6 环境中,对象实际上是排序的。
我正在尝试通过其数字键(对应于 UNIX 时间戳)对对象进行排序。这是来自后端的内容,嗯,实际上,这就是 JS 所看到的。在后端,它们被正确排序:
{
"1577837255": {
"title": "Title 1",
"message": "Message 1",
"tags": [
"tag1",
"tag2"
],
"time": 1577837255
},
"1577837260": {
"title": "Title 2",
"message": "Message 1",
"tags": [
"tag1"
],
"time": 1577837260,
}
}
问题是,在我看来,我需要按时间顺序显示这些,但是......正如你所看到的,这1577837255是第一个,而不是1577837260(更大意味着更新)。所以我踏上了一段漫长的旅程,去发现关于 ES6 对象实现的事情,Map等等。我到达了以下行:
Object.keys(notifications).sort((a,b) => {return b - a;}).forEach((key) => { console.log(notifications[key]);});
实际上,它实际上按我想要的顺序输出它们。但是看看当我将该结果分配回另一个我可以使用的对象时会发生什么:
//We're inside the loop.
someNewObject[key] = notifications[key];
它应该给我一个与我想的相同的结果,但我必须记住,ES6 本身在我自己完成后再次订购这些。
我怎样才能保持来自我刚刚进行的排序的顺序,以便我可以在循环外使用它?
这是我想要实现的一个片段:
const notifications = {
"1577837255": {
"title": "Title 1",
"message": "Message 1",
"tags": [
"tag1",
"tag2"
],
"time": 1577837255
},
"1577837260": {
"title": "Title 2",
"message": "Message 1",
"tags": [
"tag1"
],
"time": 1577837260,
}
}
let sortedNotifications = {};
console.log('Here are our sorted keys:');
Object.keys(notifications).sort((a,b) => {return b - a;}).forEach((key) => {
console.log(key);
//Now let's try to save our results to an outside objects so that we can use them.
sortedNotifications[key] = notifications[key];
});
console.log('...and maybe I saved them to an outside object in the order you just saw. Or did I? Check the keys order of the new object:');
console.log(Object.keys(sortedNotifications));
我究竟做错了什么?
在查看了许多在启用 ES6 的环境中运行的对象后,我质疑“等等,对象真的没有排序吗?”,事实证明它们实际上是:
https://exploringjs.com/es6/ch_oop-besides-classes.html#_traversal-order-of-properties
所以,我去测试并不断地颠倒项目的顺序,只是为了发现最终的对象总是一样的。很好,但我需要