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.

2
  • 1
    Object properties don't have any order, so you'll have to create an array if you want that data sorted. Commented Sep 9, 2017 at 4:26
  • @MattGregory How? Commented Sep 9, 2017 at 4:27

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

They are sorted by their keys automatically That's not exactly right. It's better to just say "their order is undefined".
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)));

1 Comment

it's preferable to use localeCompare.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.