Home > Mobile >  Performant way to convert Json to Array using Javascript
Performant way to convert Json to Array using Javascript

Time:02-19

I am using Google Chart with Data coming from back end.

I have to convert the JSON data which I retrieve from the server.

The following function is working fine and giving what I wish,

but I'm asking if there is more performant way (without loop ?) to convert data from Json to Array.

Input Json Data

[{ "W": 1, "rec": 0, "tr": 0, "Open": 24 }, { "W": 2, "rec": 43, "tr": 40, "Open": 27 }, { "W": 3, "rec": 26, "tr": 34, "Open": 19 }, { "W": 4, "rec": 53, "tr": 50, "Open": 22 }, { "W": 5, "rec": 53, "tr": 56, "Open": 19 }, { "W": 6, "rec": 40, "tr": 34, "Open": 25 }, { "W": 7, "rec": 37, "tr": 38, "Open": 24 }, { "W": 8, "rec": 45, "tr": 44, "Open": 25 }]

Output Array Data

[["W","rec","tr","Open"], [1,0,0,24], [2,43,40,27], [3,26,34,19], [4,53,50,22], [5,53,56,19], [6,40,34,25], [7,37,38,24], [8,40,42,22]]

function JsontoTable(obj) {        
    var myarray = [];
    var keys = [];
    for (var k in obj[0]) keys.push(k);
    myarray.push(keys);
    
    for (let i = 0; i < obj.length; i  ) {
        var arr = [];
        for (var k in obj[i]) { arr.push(obj[i][k]); }
        myarray.push(arr);
    }
    return (myarray);}

CodePudding user response:

let inputArray = [{ "W": 1, "rec": 0, "tr": 0, "Open": 24 }, { "W": 2, "rec": 43, "tr": 40, "Open": 27 }, { "W": 3, "rec": 26, "tr": 34, "Open": 19 }, { "W": 4, "rec": 53, "tr": 50, "Open": 22 }, { "W": 5, "rec": 53, "tr": 56, "Open": 19 }, { "W": 6, "rec": 40, "tr": 34, "Open": 25 }, { "W": 7, "rec": 37, "tr": 38, "Open": 24 }, { "W": 8, "rec": 45, "tr": 44, "Open": 25 }];

const outputArray = [Object.keys(inputArray[0])].concat(inputArray.map(Object.values));

console.log(outputArray);

  • Related