Sunil Bamal
Sunil Bamal

Reputation: 117

How to preserve the order of keys while parsing JSON object

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);
        }
    } 

enter image description here

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

Answers (1)

Uday Hiwarale
Uday Hiwarale

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 an Object but it keeps the keys in order.

Upvotes: 3

Related Questions