我试图将数组转换为与d3.csv(...)输出相同的对象。我有一个二维数组,如下所示;
0: {Biomass: null,Coal: null,Cogeneration: null,Gas: 42,Geothermal: null
country: "AFG"}
1: {Biomass: null,Coal: 20,Cogeneration: null,Gas: 10,Geothermal: null
country: "AOL"}
2: {Biomass: null,Coal: 10,Cogeneration: null,Gas: 30,Geothermal: null
country: "GER"}
我想要的是具有与d3.csv(...)相同的输出我试图减少并使用下面,但无法弄清楚如何将数组转换为一个输出应如下所示的对象
{Biomass: null,Coal: null,Cogeneration: null,Gas: 42,Geothermal: null
country: "AFG"}
{Biomass: null,Coal: 20,Cogeneration: null,Gas: 10,Geothermal: null
country: "AOL"}
{Biomass: null,Coal: 10,Cogeneration: null,Gas: 30,Geothermal: null
country: "GER"}
代码我试过了
//output is the array
var o = {};
output.forEach((e, i) => {
return o[i] = e;
});
console.log(o);
使用reduce,只能转换第一行
const f = output.reduce((obj, item) => {
obj[item.id] = item
return obj
});
console.log(f);
如何转换数组与d3.csv(...)输出相同?我希望将数组转换为数据部分页面底部的data.csv的引用。
只需使用d3
const arr = [{Biomass: null, Coal: 20}, {Biomass: 1e2, Coal: 10}];
console.log(
d3.csvFormat(arr)
);
<script src="//d3js.org/d3-dsv.v1.min.js"></script>
如果通过二维数组表示它是一个对象,其中键是整数,而值是您感兴趣的数据对象,则可以使用该对象的myObject.values()
方法。或者,为了确保与旧版浏览器兼容,d3.values(myObject)
。