JSON issue

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 is 51 66 58, but in Opera and Chrome it is 51 58 66 Why is Jquery.each () sorted by key in opera, chrome? What can I do to keep my own order?

ps, if the keys of the array are a string, the result 51j 66j 58j is possible, opera and chrome try to convert the keys to an integer where possible

var obj = {
"51j" : { "name":"name1"},    
"66j" : { "name":"name2"},    
"58j" : { "name":"name3"}
};
+3
source share
1 answer

JavaScript objects are unordered. There is no guarantee how keys should appear when you focus on them, and JS devices are free to use whatever storage and search systems they like.

If order matters, use an array: []

:

[
    { 'foo' : '1234', 'bar' : '5678' },
    { 'foo' : 'abcd', 'bar' : 'qwer' },
    { 'foo' : 'ldng', 'bar' : 'plma' }
]
+9

Source: https://habr.com/ru/post/1761462/


All Articles