Reputation: 117
I need to preserve the order of keys while parsing json data. In the below image original keys are in order "ProgramName,Curtailment1, 2 and so on" but after parsing its arranged in alphabetical order.
I am trying below workaround to fix it but confused how to fill new array with all data in original key order.
var keys = [];
for (var key in dataset[0]) { //dataset is parsed json
if (dataset[0].hasOwnProperty(key)) {
keys.push(key);
}
}
Edit: I am getting keys in original order(in keys array) after iterating keys as shown in above but the problem is i don't know to fetch all records after mapping keys.
Upvotes: 3
Views: 3350
Reputation: 4157
An Object
keys in JavaScript are not ordered unlike Array
. Hence when you use Object.keys()
or use for/in
loop on the objects, keys are not promised to be returned in a fixed order.
To solve this issue, you should convert your Data Structure to an Array
format. For example, change { "CurtailmentDT1": "High Icon", "CurtailmentDT2": "Medium Icon" }
to [ "High Icon", "Medium Icon" ]
or use a order
key to maintain the index such as
{
"CurtailmentDT1": { "index": 1, "value": "High Icon" },
"CurtailmentDT2": { "index": 2, "value": "Medium Icon" }
}
Using the index
key, you can sort the keys/values in JSON.
You can also use
Map
Data Structure which is more like anObject
but it keeps the keys in order.
Upvotes: 3