3

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.

Sofus Øvretveit
  • 323
  • 1
  • 3
  • 10

2 Answers2

5

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

Maciek Jurczyk
  • 555
  • 3
  • 7
  • 1
    *They are sorted by their keys automatically* That's not exactly right. It's better to just say "their order is undefined". –  Sep 09 '17 at 04:34
3
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)));
Bharti Ladumor
  • 1,624
  • 1
  • 10
  • 17