Chrome and IE sort JSON Object automatically, how to disable this?

I use the following JSON to create multiple checkboxes using JavaScript.

{"5":"5.5\" x 8.5\"", "11":"7\" x 10\"", "4":"8.5\" x 11\"", "8":"8.5\" x 14\"", "12":"10\" x 7\"", "2":"11\" x 8.5\"", "10":"11\" x 17\"", "6":"14\" x 8.5\"", "9":"17\" x 11\""}) 

JavaScript to create these checkboxes:

 for(id in dimensions) { $("#the_dimensions").append('<label class="checkbox">' + '<input type="checkbox" class="dimensions-filter" value="' + id + '">' + dimensions[id] + '</label>'); } 

In Firefox, a check box is created according to the order in the JSON object. So, "5": "5.5 \" x 8.5 \ "becomes the first element," 11 ":" 7 \ "x 10 \" "becomes the second element, etc.

But in Chrome and IE, the JSON object is sorted automatically in ascending order of keys. So, "2": "11 \" x 8.5 \ "becomes the first element," 4 ":" 8.5 \ "x 11 \" "becomes the second element and so on.

How to disable automatic sorting by Chrome and IE?

+2
source share
1 answer

Same problem here. My JSON object looks like this:

 { "15" : { "name" : "abc", "desc" : "Lorem Ipsum" }, "4" : { "name" : "def", "desc" : "Foo Bar Baz" }, "24" : { "name" : "ghi", "desc" : "May be" }, "8" : { "name" : "jkl", "desc" : "valid" } } 

The object is sorted by name on the server (glossary AZ), and I want to display the list with:

 var data = myObject, i; console.log(data); for (i in data) { if (data.hasOwnProperty(i)) { // do stuff } } 

Chrome logs:

 Object {4: Object, 8: Object, 15: Object, 24: Object} 

and my for-in loop leads to wrong sorting. It is automatically sorted by the browser, but I need identifiers.

My decision:
I decided to change the keys with an underscore prefix. Now my object looks like:

 { "_15" : { "name" : "abc", "desc" : "Lorem Ipsum" }, "_4" : { "name" : "def", "desc" : "Foo Bar Baz" }, "_24" : { "name" : "ghi", "desc" : "May be" }, "_8" : { "name" : "jkl", "desc" : "valid" } } 

Now Chrome logs:

 Object {_15: Object, _4: Object, _24: Object, _8: Object} 

And my list is displayed correctly.

+11
source

All Articles