繁体   English   中英

如何在JavaScript中将多维对象转换为表格行列格式

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

我的ajax响应中有一个多维对象。 这是对象

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

现在我想将该数组重新排列为谷歌图表数据表格式,如下

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

那很难,我相信它可以改善。 看评论

 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> 

不确定基于提供的响应,数字数组中的第三项来自何处,但是至少这会使您指向正确的方向:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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