-1

I am having a problem while receiving a response from the server. The JSON has the following structure (as I can see on the network from the navigator):

{ "33": { "id": "...", "name":"..." }, "11": { "id": "...", "name":"..." }, "22": { "id": "...", "name":"..." } }

However, when I see the variable containing the response, the structure is changed and ordered like this:

{ "11": { "id": "...", "name":"..." }, "22": { "id": "...", "name":"..." }, "33": { "id": "...", "name":"..." } }

There is someway to mantain the same order that the actual response when I receive the variable response from the successfull callback of the request on angularJS?

Thanks in advance!

user3429953
  • 352
  • 3
  • 19

3 Answers3

2

From the spec:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

Objects in JSON are explicitly unordered. If you need order, then use an array instead.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I think I cannot use an array, since the Object I am talking about is the JSON parsed into that Object, as Pawel said on the other comment. And I dont need to order following any restriction, only to mantain the same order as the response from the server – user3429953 Sep 09 '16 at 09:22
  • @user3429953 — The response from the server does not have an order. It is sending you an object. Objects are explicitly unordered. For it to have an order the server would have to send you an array instead of an object. – Quentin Sep 09 '16 at 09:24
  • ok! Thanks for the answer, I finally understand what all of you are saying. – user3429953 Sep 09 '16 at 09:34
-1

You need get the server side data with order by.

Ramesh R
  • 13
  • 5
-1

After JSON is parsed it turns into an object. In an object order of parameters is not sorted in a predictable way. Use an array instead of an object

Old:

{ "33": { "id": "...", "name":"..." }, "11": { "id": "...", "name":"..." }, "22": { "id": "...", "name":"..." } }

New:

{ [{ "id": "33", "name":"..." }, { "id": "11", "name":"..." }, { "id": "22", "name":"..." }] }

Now you'll have an array with order exactly as you put it. Use Lodash to operate on your data.

Possibly a duplicate of this: JSON order mixed up

Community
  • 1
  • 1
Pawel
  • 16,093
  • 5
  • 70
  • 73