2

I have a JSON file formatted like below:

{
    "dislike": 0,
    "like": 15,
    "laugh": 4
}

How can I sort the JSON in descending order, so that it looks like this:

{
    "like": 15,
    "laugh": 4,
    "dislike": 0
}

Any help would be much appreciated. Thank you!

  • 1
    objects are meant to be unordered, if you have to sort them maybe convert it to an array, sort it, then convert it back to an object – Chris Li Aug 04 '22 at 17:54
  • 1
    It looks like [this post](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) answers what you need. – EssXTee Aug 04 '22 at 17:55

1 Answers1

1

I'm using object.entries() to transform the object in an array of entries [["dislike", 0], ["like", 15], ["laugh", 4]] to use the sort method, so I can order by the position [1] of each element in the array that is the entry value.

At the end transform the entries in an object again using Object.fromEntries()

json = {
    "dislike": 0,
    "like": 15,
    "laugh": 4
}

const entriesResult = Object.entries(json).sort((v1, v2) => v2[1] - v1[1])

const resultObject = Object.fromEntries(entriesResult)

console.log(resultObject)
Briuor
  • 278
  • 1
  • 9
  • This is actually a lot cleaner of an approach than the [other answer](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) people suggested! Thank you! –  Aug 04 '22 at 18:16