Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - Sort JSON objects by a value [duplicate]

I have this JSON file on my server:

{"1504929411112":{"name":"user1","score":"10"},"1504929416574":{"name":"2nduser","score":"14"},"1504929754610":{"name":"usr3","score":"99"},"1504929762722":{"name":"userfour","score":"40"},"1504929772310":{"name":"user5","score":"7"}}

Assuming I have parsed this file:

var json = JSON.parse(getJSONFile());

How can I now sort each object in the json variable by the score property? None of the array sorting functions work for me as json is not an array.

like image 452
Sofus Øvretveit Avatar asked Sep 27 '26 11:09

Sofus Øvretveit


2 Answers

Since these are objects' properties, their order is usually unknown and not guaranteed. To sort them by some internal property, you would first have to change the Object into an Array, for example:

const json = JSON.parse(getJsonFile());

const jsonAsArray = Object.keys(json).map(function (key) {
  return json[key];
})
.sort(function (itemA, itemB) {
  return itemA.score < itemB.score;
});

For more, see:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

like image 91
Maciek Jurczyk Avatar answered Sep 29 '26 21:09

Maciek Jurczyk


var ob = { "fff": { "name": "user1", "score": "10" }, "bbbb": { "name": "user4", "score": "14" }, "dddd": { "name": "user2", "score": "99" }, "cccc": { "name": "user5", "score": "40" }, "aaaa": { "name": "user3", "score": "7" } };


Object.keys(ob).map(key => ({ key: key, value: ob[key] })).sort((first, second) => (first.value.name < second.value.name) ? -1 : (first.value.name > second.value.name) ? 1 : 0 ).forEach((sortedData) => console.log(JSON.stringify(sortedData)));
like image 33
Bharti Ladumor Avatar answered Sep 29 '26 21:09

Bharti Ladumor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!