-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!

4
  • Server? Are you using nodejs? Commented Sep 9, 2016 at 9:10
  • Hello, the server is being developed by other site, but they are using PHP + NGINX Commented Sep 9, 2016 at 9:13
  • Null. you are getting back an object, the keys happen to be numbers. but an object is an un-ordered set. if order is important you must use the JavaScript array. Commented Sep 9, 2016 at 9:16
  • Yeah, thats the problem. If the keys would have been strings and not numbers it works correctly... Commented Sep 9, 2016 at 9:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 — 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.
ok! Thanks for the answer, I finally understand what all of you are saying.
-1

You need get the server side data with order by.

Comments

-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.