M
M
My joy2018-03-21 17:11:37
JavaScript
My joy, 2018-03-21 17:11:37

How to sort an object?

There is an object:

{
  "10": {
    "name": "The Name",
    "count": "4"
  },
  "9": {
    "name": "Some name",
    "count": "7"
  }
  ...
  "1": {
    "name": "Bla bla",
    "count": "6"
  }
}


But before displaying this in a user-readable table, it turns out to be with direct sorting (1-9), and I need the same sorting as it came from the server (9-1). How can I prevent javascript from sorting when converting to json? Or how to sort an object back in descending order?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2018-03-21
@t-alexashka

Make an array out of the object and sort it as you need:

Object.entries(data).map(([ key, val ]) => ({ ...val, id: key })).sort((a, b) => b.id - a.id)

M
mortyy, 2018-03-21
@mortyy

you need to change the keys to non-numeric

S
Stalker_RED, 2018-03-21
@Stalker_RED

No way. Use some other data structures.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question