1

In our Angular7 frontend application, we are receiving a JSON response from the backend server. Response data is already sorted in the backend using some domain-specific logic.

Sample response

{
    "a": ["test1", "test2"],
    "b": ["test3", "test4"],
    "c": ["test5", "test6"]
}

Now we want to display the response in HTML and we should not change the order of the JSON keys while displaying, we should maintain the same order what we received from the backend, just like below

a

test1

test2

b

test3

test4

c

test5

test6

I'm using the following code to achieve this but not sure whether it displays in the same order always or not

Object.entries(this.response).forEach(([key, value]) => {
      response += `${key}\n`;
      response += value.join('\n')+'\n\n';
    });

How to maintain the original order while iterating&displaying JSON object in JavaScript

Rams
  • 2,141
  • 5
  • 33
  • 59
  • According to the JSON spec, JSON dictionaries are naturally unordered. See: https://stackoverflow.com/questions/32006162/keep-order-of-objects-inside-a-json-string-after-they-are-parsed – Ouroborus Jan 22 '21 at 10:18
  • You don't really need to modify the object in the controller to display it in the template. You could use `*ngFor` with `keyvalue` pipe to iterator over the object. You could then adjust the sort order using the `keyvalue` pipe's optional `compareFn` argument. See here for more info: https://stackoverflow.com/a/52794221/6513921 – ruth Jan 22 '21 at 10:21
  • But what unexpected result are you getting? Are your values mixed up in your Angular view? – Kokodoko Jan 22 '21 at 10:24

0 Answers0