Chrome和IE自动排序JSON对象,如何禁用此?(Chrome and IE sorts JSO

2019-07-19 00:31发布

我使用下面的JSON创建使用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来创建这些复选框是:

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 \” ×8.5 \ “” 变为第一元件, “11”: “7 \” ×10 \ “” 变为第二元件,等等。

但在Chrome和IE中,JSON对象就会自动在按键的升序排序。 所以, “2”: “11 \” ×8.5 \ “” 成为第一元件 “4”: “8.5 \” ×11 \ “” 变为第二元件,等等。

我怎么能在Chrome和IE浏览器禁用自动排序?

Answer 1:

同样的问题在这里。 我的JSON对象看起来是这样的:

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

目的是通过在名称服务器(AZ词汇表)进行分类,我想渲染列表:

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}

和我换在错误的排序循环的结果。 它是由浏览器自动排序,但我需要的ID。

我的解决方案:
我决定用一个前缀下划线来更改密钥。 现在我的目标如下:

{
  "_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记录:

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

而我的列表呈现正确。



文章来源: Chrome and IE sorts JSON Object automatically, how to disable this?