Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - Chrome and IE sorts JSON Object automatically, how to disable this?

I am using the following JSON to create few 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""})

The JavaScript to create those checkboxes is:

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

On Firefox, the checkbox is created as per 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, so on.

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

How can I disable auto sorting on Chrome and IE?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 at server (A-Z glossary) and I want to render a 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 results in wrong sort. It's automatically sorted by the browser, but I need the IDs.

My solution:
I decided to change the keys with a prefixed underscore. My object looks now:

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

And Chrome logs now:

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

And my list is rendered correct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...