0

my object:

0: {
    id: 20050,
    name: "something",
    date: "2021-01-28 16:46:02",
},
1: {
    id: 20054,
    name: "other something",
    date: "2021-01-28 12:25:57",
},
2: {
    id: 20059,
    name: "again something",
    date: "2021-02-15 07:01:34",
},

I map it like this:

Object.keys(myObj).forEach(function(item, index) {
    myObj[item].id // returns myObj id value
    myObj[item].name // returns myObj name value
});

I need to sort by the most recent or oldest date, and I have no idea how to use "myObj.sort" with the type of object I have here

Isaque Palmieri
  • 97
  • 2
  • 2
  • 9
  • Does this answer your question? [How to sort an object array by date property?](https://stackoverflow.com/questions/10123953/how-to-sort-an-object-array-by-date-property) – Nick Parsons Feb 20 '21 at 01:56
  • No @NickParsons, my array is not that way, he has keys. anyway try to do the same but it didn't work – Isaque Palmieri Feb 20 '21 at 02:02
  • Please add your array, before your question had `items[index] = myObj[item];`, which seemed as though you are populating an `items` array which you wanted to sort. Can you also please add your expected result to the question? – Nick Parsons Feb 20 '21 at 02:03

2 Answers2

2

Convert your object to array for sorting and then revert back.

const obj = {
  0: {
    id: 20050,
    name: 'something',
    date: '2021-01-28 16:46:02'
  },
  1: {
    id: 20054,
    name: 'other something',
    date: '2021-01-28 12:25:57'
  },
  2: {
    id: 20059,
    name: 'again something',
    date: '2021-02-15 07:01:34'
  }
};

// convert obj to arr
const values = Object.values(obj);

// sort by date
values.sort((a, b) => new Date(b.date) - new Date(a.date));

// convert arr to obj
const res = { ...values };

console.log(res);
michael
  • 4,053
  • 2
  • 12
  • 31
0

This will convert the dates into a parseable form (by replacing the space with a T so that it ends up YYYY-MM-DDTHH:MM:SS) and then sort them:

let result = Object.values(myObj).sort((a,b) => 
 new Date(b.date.replace(" ","T")) - new Date(a.date.replace(" ","T"))
)

This does get rid of the initial object keys (0,1,2,etc), which I'm assuming you don't need since they have individual IDs, but if you did need them, you could copy them into the object structure first before sorting.

jnpdx
  • 45,847
  • 6
  • 64
  • 94