不負相思意
2023-09-28 09:42:39
我正在嘗試使用 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
提交
取消