0

Currently I have a small piece of code which loops through a json object:

for (var key in json_object) {
    if (json_object.hasOwnProperty(key)) {
        var value       = key; //e.g. 50_100, 1000_2000, 20_50 etc
    }
}

I'm going to be outputting these values into a list later on. But the problem is that these values aren't in any order right now.

I'd like to be able to have these values sorted out in order. So my question is, is this possible and if so how?

Thanks!

user2028856
  • 3,063
  • 8
  • 44
  • 71

2 Answers2

1

In javascript, object properties are not guaranteed a specific order, so if you want to maintain order, you would likely need to write the object properties into an array of objects.

That could look like this:

var object_array = [];
// map properties into array of objects
for (var key in json_object) {
    if (json_object.hasOwnProperty(key)) {
        object_array.push({
            'key': key;
            'value': value;
        });   
    }
}
// sort array of objects
object_array.sort(function(a,b) {
    // note that you might need to change the sort comparison function to meet your needs
    return (a.value > b.value);
}
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • I tried this but it doesn't seem to perform any sorting for strings such as this "100_500" , "800_1000", "2000_3000" etc – user2028856 Mar 16 '16 at 14:40
  • @user2028856 That is why I indicated that you might need to change the sort comparison to do something applicable to the values you are sorting by. In the case of your strings, how would you propose to perform the sort? – Mike Brant Mar 16 '16 at 16:45
  • Your comparison function is invalid, see [Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?](http://stackoverflow.com/q/24080785/1048572) – Bergi Mar 16 '16 at 20:31
0

After reading all solutions, I realized my solution was wrong. Object.keys is good for getting an array of keys only, so Mike Brant's solution is correct, although a little fix is needed since value is not a variable there. Finally here's a fixed solution based on his solution + the requested sorting from the comments:

var arr = [];

for (var key in json_object) {
    if (json_object.hasOwnProperty(key)) {
        arr.push({
            'key': key;
            'value': json_object[key];
        });   
    }
}

// this will sort by the first part of the string
arr.sort(function(a, b) {
  return a.key.split('_')[0] - b.key.split('_')[0];  
}

Hope this helps... :-)

Asaf David
  • 3,167
  • 2
  • 22
  • 38