javascriptjsonajaxjavascript-objects

Prevent sorting with for-in loop in Javascript


I have the following JSON array sorted by type (rather than ID).

var response = {"5":"Contacts","2":"Messages","3":"Profiles","1":"Schools","4":"Statistics"};
for (var key in response) {
    alert(key + ' ' + response[key]);
}

I am wanting the order to stay as is however what is happening is that it is sorting it by ID so that it produces "1 Schools" first. How do I prevent a for-in loop from sorting by key?

I realize that no sorting order is guaranteed with a for-in loop, so how do I get around this? I need to access both the key and type. Is there a different type of array and/or loop that I should be using instead?

Also, just for further clarification and in case it makes a difference, my actual code has the JSON array coming from an AJAX request from PHP using json_encode.


Solution

  • You do not have an array, you have an object. Key ordering in an object is not guaranteed in javascript. If you want a sorted collection, you should use an actual array:

    var response = [{"key":"5", "value":"Contacts"},{"key":"2", "value":"Messages"},{"key":"3", "value":"Profiles"},{"key":"1", "value":"Schools"},{"key":"4", "value":"Statistics"}];
    for (var i =0; i < response.length; i++) {
        alert(response[i].key + ' ' + response[i].value);
    }