Search code examples
javascriptjqueryjson

Loop through json object and sort in order


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!


Solution

  • 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);
    }