3
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"}
};
asked Aug 25, 2010 at 6:19
3
  • It's object keys, and they're strings whatever happens. Commented Aug 25, 2010 at 9:35
  • it's seems opera and chrome do not think so.. Commented Aug 25, 2010 at 9:49
  • In JS, obj[1] and obj['1'] are equivalent. However, as already explained the order of for..in iteration is left undefined by the specification. Browsers can return the values in ANY order and still behave "correctly" per the specification. Over time, compatibility with the web and other browsers has forced insertion order most of the time, but this is still not reliable as you've discovered. Commented Aug 27, 2010 at 3:24

1 Answer 1

9

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' }
]
answered Aug 25, 2010 at 6:22
Sign up to request clarification or add additional context in comments.

2 Comments

If i get it via ajax request?
@ncsft: If you cannot change the JSON you need to read it in and sort it yourself, before processing.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.