At the bottom, there's a bit of explanation as to how I ended up here. In an ES6 environment, objects are actually sorted.
I'm trying to order an object by its numerical keys (which correspond to UNIX timestamps). Here's what's coming from the back-end, well, actually, this is what JS sees. In the back-end, they are properly ordered:
{
"1577837255": {
"title": "Title 1",
"message": "Message 1",
"tags": [
"tag1",
"tag2"
],
"time": 1577837255
},
"1577837260": {
"title": "Title 2",
"message": "Message 1",
"tags": [
"tag1"
],
"time": 1577837260,
}
}
Problem is, in my view, I need to display these in order of time, but...as you can see, the 1577837255
is first, not 1577837260
(bigger means newer). So I went on a long journey of discovering things about ES6 implementation of objects, Map
and so on. I reached the following line:
Object.keys(notifications).sort((a,b) => {return b - a;}).forEach((key) => { console.log(notifications[key]);});
Which, indeed, actually outputs them in the order I want. But look what happens when I assign that result back to another object that I can use:
//We're inside the loop.
someNewObject[key] = notifications[key];
It should give me an identical result I thought, but I have to remember that ES6 itself orders these once again after I'm done myself.
How can I maintain that order coming from the sorting I just did so that I can use it outside the loop?
Here's a snippet of what I'm trying to achieve:
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));
What am I doing wrong?
After looking at a lot of objects that run in an ES6 enabled environment, I questioned "wait, are objects really not ordered?", turns out they actually are:
https://exploringjs.com/es6/ch_oop-besides-classes.html#_traversal-order-of-properties
So, I went to test and reversed the order of items constantly just to find out the end object would always be the same. That's great, but I need