views:

41

answers:

1
+1  Q: 

Problem with JSON

var obj = {
'51' : { 'name':'name1'},     
'66' : { 'name':'name2'},     
'58' : { 'name':'name3'}
};
$(function() {
    s = '';
    $.each(obj, function(k, v) {
        s += ' '+k;
    });
    alert(s);
});

In IE and Firefox it's 51 66 58, but in Opera and Chrome it's 51 58 66 Why Jquery.each() sort by key in opera, chrome? What can i do to keep native order?

p.s if array keys is a string, result 51j 66j 58j perhaps opera and chrome try to convert keys to integer where it's possible

var obj = {
"51j" : { "name":"name1"},    
"66j" : { "name":"name2"},    
"58j" : { "name":"name3"}
};
+7  A: 

JavaScript objects are unordered. There is no guarantee about which order the keys should come out when you loop over them and JS engines are free to implement whatever storage and retrieval systems they like.

If order matters, use an array: []

This can contain objects:

[
    { 'foo' : '1234', 'bar' : '5678' },
    { 'foo' : 'abcd', 'bar' : 'qwer' },
    { 'foo' : 'ldng', 'bar' : 'plma' }
]
David Dorward
If i get it via ajax request?
ncs
@ncsft: If you cannot change the `JSON` you need to read it in and sort it yourself, before processing.
jAndy