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

时间:2016-12-04 04:03:42

标签: javascript json multidimensional-array

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

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

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

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

2 个答案:

答案 0 :(得分:2)

这很难,我相信它可以改进。见评论

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>

答案 1 :(得分:0)

根据提供的响应,不确定数值数组中的第三项是什么,但至少这会让你指向正确的方向:

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