我正在尝试使用 d3.js v5 解压 csv 以进行数据可视化,但收到以下控制台错误:Uncaught TypeError: data.reduce is not a function这是我的代码中给我带来错误的部分:sample();function sample() {const data = d3.csv('../static/sample.csv');uncount = (data, accessor) => data.reduce((arr, item) => { const count = accessor(item) for (let i = 0; i < count; i++) { arr.push({ ...item }) } return arr }, []);const boxes = uncount(data, d => d.boxes);const nest = d3 .nest() .key(d => d.venue) .entries(boxes);}但是,如果我像这样切换数据对象(而不是 csv 中的行读取),它会起作用:const data = [{ "year": 2015, "tour": "The Red Bullet", "venue": "Rosemont theatre", "capacity": 4400, "boxes": 18 }, { "year": 2017, "tour": "Wings", "venue": "Allstate arena", "capacity": 18500, "boxes": 74 }, { "year": 2018, "tour": "Love Yourself", "venue": "United center", "capacity": 23500, "boxes": 94 }, { "year": 2019, "tour": "Love Yourself - Speak Yourself", "venue": "Soldier Field", "capacity": 61500, "boxes": 246 }];这是因为 D3 v5 使用 fetch api 返回 Promise 吗?
1 回答
白衣非少年
TA贡献1155条经验 获得超0个赞
这是因为 D3 v5 使用 fetch API 返回承诺吗?
是的。Promise 没有reduce
方法。一个简单的解决方案是更改sample
为async function,然后await
更改值。
sample();
async function sample() {
const data = await d3.csv('../static/sample.csv');
uncount = (data, accessor) =>
data.reduce((arr, item) => {
const count = accessor(item)
for (let i = 0; i < count; i++) {
arr.push({
...item
})
}
return arr
}, []);
const boxes = uncount(data, d => d.boxes);
const nest = d3
.nest()
.key(d => d.venue)
.entries(boxes);
}
请注意,异步函数始终返回一个承诺。
添加回答
举报
0/150
提交
取消