Chrome 和 IE 自动对 JSON 对象进行排序,如何禁用它? [英] Chrome and IE sorts JSON Object automatically, how to disable this?

查看:46
本文介绍了Chrome 和 IE 自动对 JSON 对象进行排序,如何禁用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下 JSON 来使用 JavaScript 创建几个复选框.

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""})

创建这些复选框的 JavaScript 是:

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>');
}

在 Firefox 上,复选框是按照 JSON 对象中的顺序创建的.因此,"5":"5.5" x 8.5"" 成为第一个元素,"11":"7" x 10"" 成为第二个元素,以此类推.

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.

但是在 Chrome 和 IE 上,JSON 对象会按照键的升序自动排序.因此,"2":"11" x 8.5"" 成为第一个元素,"4":"8.5" x 11"" 成为第二个元素,以此类推.

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.

如何在 Chrome 和 IE 上禁用自动排序?

How can I disable auto sorting on Chrome and IE?

推荐答案

同样的问题.我的 JSON 对象如下所示:

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" }
}

对象在服务器上按名称排序(A-Z 词汇表),我想呈现一个列表:

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 日志:

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

并且我的 for-in 循环导致排序错误.它由浏览器自动排序,但我需要 ID.

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" }
}

Chrome 现在记录:

And Chrome logs now:

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

我的列表呈现正确.

这篇关于Chrome 和 IE 自动对 JSON 对象进行排序,如何禁用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆