jquery sorts my date automatically

Asked

Viewed 116 times

1

I send a json to any url, like this one:

{"130":"chocolate","129":"banana","120":"chiclete"}

Then I’ll get $.

$.get(url,function(data){
   console.debug(data);
},'json');

result ( it sorts automatically, without me needing):

Object { 120="chiclete", 129="banana", 130="banana"}

1 answer

1

In Javascript, objects are ensembles key pairs/value. Sets, by definition, have no order. {1,2,3} == {1,3,2} == {2,1,3} etc. When printing on the console, an order is arbitrarily chosen (which, in this case, was in ascending order of the keys), but this does not mean that the object is actually ordered, nor that in all situations the iteration/use/printing order will be the same.

If you really need of a defined order - be the order the server sent, be any sort of sorting defined by you via Javascript - so don’t use objects, use arrays of arrays:

[["130","chocolate"],["129","banana"],["120","chiclete"]]

Otherwise, the browser can and will change the [usage] order as well as understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.