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

3
  • Does this answer your question? How to sort an object array by date property? Commented Feb 20, 2021 at 1:56
  • No @NickParsons, my array is not that way, he has keys. anyway try to do the same but it didn't work Commented Feb 20, 2021 at 2: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? Commented Feb 20, 2021 at 2:03

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.