[英]How can I convert multidimensional object to table row column format in javascript
I have got a multidimensional object in my ajax response. 我的ajax响应中有一个多维对象。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.