簡體   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