简体   繁体   中英

How can I convert multidimensional object to table row column format in javascript

I have got a multidimensional object in my ajax response. Here is the object

 response = {
             "Bangladesh": {
                 "2016": 5,
                 "2017": 1
            },
            "Nepal": {
                "2016": 1,
                "2019": 10
            }
    };

Now I want to rearrange that array to a google chart Data table format as bellow

['Year', 'banglladesh', 'nepal' ],
['2016', 5,1],
['2017',  1,0],
['2019',  0, 10],

That was hard, I'm sure it can be improved. see comments

 const response = { "Bangladesh": { "2016": 5, "2017": 1 }, "Nepal": { "2016": 1, "2019": 10 } }; const parse = val => isNaN(val) ? val : Number(val) const tablerize = (obj, unique) => { const columns = Object.keys(obj) const table = [[unique, ...columns]] // indexed by the unique key const indexed = {} // sort by the index columns.forEach((key, ii) => { return Object.keys(obj[key]).forEach((prop) => { if (!indexed[prop]) { indexed[prop] = {} } indexed[prop][ii] = obj[key][prop] }) }) // add to the output table Object.keys(indexed).forEach(key => { table.push([ parse(key), // return the value at the key index ...columns.map((k, ii) => parse(indexed[key][ii]) || 0) ]) }) return table } console.log( tablerize(response, 'Year') ) 
 <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> 

Not sure what the third item in the numeric arrays are coming from based on the response provided, but at least this will get you pointed in the right direction:

var response = {
  "Bangladesh": {
        "2016": 5,
        "2017": 1
   },
   "Nepal": {
       "2016": 1,
       "2019": 10
   }
};

var out = [];

var header = ["Year"];
out.push(header);

for(var prop in response){
    header.push(prop);
    var item = response[prop];
    for(var year in item){
        out.push([year, item[year] ] );
    }
}

console.log(out);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM