简体   繁体   中英

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.

How do I prevent a for-in loop from sorting by key?

You can't. The iteration order is unspecified and implementation depended 1 . If you need to traverse your data in a predefined order, use an array instead.


1: Most popular browsers will iterate over numeric properties in ascending order and then non-numeric properties in insertion order, but again, that's an implementation detail.

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

If you don't have access to the server but the order of the key is guaranteed you can try the following:

Map the keys in the order you want them and loop them that way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM