0

I have a Json array as mention below

var data=  "  [{"-1":0,"0":0,"1":0,"2":1,"3":0,"4":0,"5":1,"Total":2},{"-1":0,"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"Total":0},{"-1":0,"0":0,"1":0,"2":1,"3":0,"4":0,"5":1,"Total":2},{"-1":0,"0":0,"1":0,"2":1,"3":0,"4":0,"5":1,"Total":2}]";

When I do

JSON.Parse(data);

the order is original order is missing, it shows as below

0: {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 1, -1: 0, Total: 2}
1: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, -1: 0, Total: 0}
2: {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 1, -1: 0, Total: 2}
3: {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 1, -1: 0, Total: 2}

Is there any way we can preserve the order of the parsed arry ?

Champ
  • 452
  • 1
  • 6
  • 12
  • What do you mean by `the order is original order is missing` ? – Christheoreo Jul 29 '19 at 12:05
  • 4
    The array order is correct but objects have no guaranteed order of keys...especially when keys are numeric – charlietfl Jul 29 '19 at 12:07
  • 1
    You should avoid relying on key orders with javascripts objects. Either sort them or whatever, but **never** rely on key order. – briosheje Jul 29 '19 at 12:08
  • Hi @Christheoreo, I mean the original key order, – Champ Jul 29 '19 at 12:09
  • _"Is there any way we can preserve the order of the parsed arry ?"_ The order of the parsed __array__ is still the same. The __objects__ in that array are rendered differently, because that just depends on how the browser decides to render objects. Properties in an object don't have an "order". – Cerbrus Jul 29 '19 at 12:12
  • I still don't get what the issue is – shrys Jul 29 '19 at 12:13
  • why do you need to preserve the order of keys? your example have keys in order from -1 to 5 and accessing an element from an object is of complexity O(1) if you want to put them back in ascending order you convert them into array or Map`data.map(ele => Object.assign([], ele)` – AZ_ Jul 29 '19 at 12:16

0 Answers0