Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Performant way to convert Json to Array using Javascript

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading