• I have some JSON data generated on the server-side, in some desired order, but when it gets to the browsers, the order changed. This post shows how I get around this problem.*
062-feature-image.png
JavaScript: preserving JSON data order on the client-side.

I have been working with JSON for a fair while, but this was the first time I came across this problem. To illustrate, the following screen capture shows the JSON generated by the server:

062-01.png

And the following screen image shows how it arrives at a browser:

062-02.png

JavaScript reorders the data. It turns out this is a well known problem, for example, JSON object being reordered by Javascript – and elsewhere which I am not going to list.

The general consensus seems to assign each data object to a key which we know will maintain their order alpha-numerically. I know that there are only a handful of fields within each JSON: keys in format field01 to field99 are more than adequate. Accordingly, at the server-side, I changed the JSON to:

062-03.png

Now the data arrives in the order set out by the server:

062-04.png

The JavaScript to extract the data out will be more complicated, I had to add another additional for loop. The server code, increased a little, too. The penalty we have to pay.

This was a new problem for me. I was not aware of it. So I thought I would just share my experience. I hope you find this post useful. Thank you for reading and stay safe as always.

✿✿✿

Feature image sources: