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