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

后端 未结 1 663
一个人的身影
一个人的身影 2020-12-04 00:25

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\\\"\",         


        
相关标签:
1条回答
  • 2020-12-04 00:50

    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.

    0 讨论(0)
提交回复
热议问题