1

I have an API which returns the following data and isn't in any order. What would be the best way to do this using the "created" field.

{
  "002": {
    "created": 1651570929442,
    "sub": false,
    "message": "Second Message",
    "user": "Demo"
  },
  "003": {
    "message": "Third Message",
    "created": 1651570933926,
    "user": "Demo",
    "sub": false
  },
  "001": {
    "user": "Demo",
    "created": 1651570928159,
    "sub": false,
    "message": "First Message"
  }
}
{
  Object.entries(data).map(([key, val]) =>
  <div key={key} data-id={key}>
    <div>
      <span>{val.user}</span>:
    </div>
    <div>
      {val.message}
    </div>
  </div>
  )
}
invmatt
  • 13
  • 4
  • `Object.entries(data).sort(([_, a], [__, b]) => a.created - b.created).map(` –  May 03 '22 at 10:22
  • or `.sort(([,{created:a}], [,{created:b}])=> a-b)` - @ChrisG you don't need `_` or `__` placeholders there – Bravo May 03 '22 at 10:26
  • 1
    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) –  May 03 '22 at 10:32
  • The link you send is not related to the question, @ChrisG. S/He's looking for the sort through an object, not an array like the link you sent – Nick Vu May 03 '22 at 10:41
  • @NickVu Doesn't matter; OP is using `Object.entries(data)` to get an array so the duplicate is a perfect fit. It doesn't have to be absolutely 100% exactly the same. It's about the knowledge conveyed in the question. Turning the API data into an array first is just incidental here (also, you cannot sort an Object) –  May 03 '22 at 11:59
  • By the way, I have found a more related answer for her/him. https://stackoverflow.com/questions/1069666/sorting-object-property-by-values With these references, my answer seemingly is an actual dupe. Thanks for the clarification, @ChrisG – Nick Vu May 03 '22 at 12:19
  • @NickVu I disagree (because OP is already turning the object into an array), but it doesn't matter anyway. Any easy JS question is a dupe, it's just a matter of finding it. –  May 03 '22 at 12:23

0 Answers0