6

I have a simple ajax call that looks like this:

var data = jQuery.parseJSON(response.d);

The response.d contents are:

{"d":"[[{\"ExtensionData\":{},\"categoryId\":\"Help\"}],{\"11\":\"This is 11\",\"10\":\"This is 10\",\"7\":\"This is 7\",\"6\":\"This is 6\",\"12\":\"This is 12\",\"5\":\"This is 5\",\"4\":\"This is 4\",\"2\":\"This is 2\",\"1\":\"This is 1\"}]"}

When I run the code and look at what data contains, it looks like this:

  1. "This is 1"
  2. "This is 2"
  3. "This is 3"
  4. "This is 4"
  5. "This is 5"
  6. "This is 6"

... and so on, you get the idea. Why is it sorted all of the sudden? How do I turn off the "autosort"?

nikc.org
  • 14,808
  • 5
  • 44
  • 80
RangerChris
  • 139
  • 2
  • 12
  • 2
    `parseJSON()` does not sort. Probably this is more related to your way of traversing the resulting array. – Sirko Jan 27 '15 at 08:59
  • 3
    Take a look at this: [Does JavaScript Guarantee Object Property Order?](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – llernestal Jan 27 '15 at 09:00
  • @Sirko: `parseJSON` doesn't sort *at all*. No "really" about it. – T.J. Crowder Jan 27 '15 at 09:00
  • @ RangerChris: How can we help if you don't show *how* you're getting that output? – T.J. Crowder Jan 27 '15 at 09:01
  • Well, all I can see is that the data I get from the service looks good. If I parse the json, the data is ordered and when I loop them with a simple for-loop they come out in an ordered way. – RangerChris Jan 27 '15 at 09:12
  • for (var windowsize in data[1]) { jQuery(".windowsize").append(new Option(data[1][windowsize], windowsize)); } – RangerChris Jan 27 '15 at 09:13

2 Answers2

12

Retaining object key order between unserialisation and serialisation in JavaScript is never guaranteed. The only way to guarantee key order is to extract an object's keys and sort them according to a deterministic criteria, i.e. in order to guarantee order, you must use an array.

Edit:

A possible solution to your problem would be to include an array of the object keys in addition to your key-value collection (the original object) to your server response. By iterating over the ordered keys, you can access the object in the order you want.

E.g.

var data = { 
    values: { /* your original object here */ },
    /* keep a record of key order and include the keys as an array 
       in your response. That way you can guarantee order. */
    keys: [11, 10, 7, 6, 12, 5, 4, 2, 1]
};

data.keys.forEach(function (key) {
   var value = data.values[key];

   /* do work here */
});
nikc.org
  • 14,808
  • 5
  • 44
  • 80
-4

jQuery.parseJSON(); does not not sort your objects. But some browsers do sorting your objects after rendering. For clarification see here

Community
  • 1
  • 1