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:
... and so on, you get the idea. Why is it sorted all of the sudden? How do I turn off the "autosort"?
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 */
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With