gpt4 book ai didi

javascript - d3 数据 reshape : properties to array

转载 作者:行者123 更新时间:2023-11-30 20:30:44 27 4
gpt4 key购买 nike

我有一些这种格式的数据:

{
seriesOne: [
[1, 42.3],
[2, 12.9]
],
seriesTwo: [
[1, 23.1],
[2, 10.6]
]
}

但我正在查看 D3 example数据最终采用这种格式:

[{
id: "seriesOne",
values: [{
x: 1,
y: 42.3
},
{
x: 2,
y: 12.9
}
]
},
{
id: "seriesTwo",
values: [{
x: 1,
y: 23.1
},
{
x: 2,
y: 10.6
}
]
}
]

我可以按原样绘制图表吗?或者,有没有一种 D3 方法可以 reshape 我的数据?

我可以用普通的旧 JS reshape 它,但这看起来效率很低。

var reshapedData = [];
Object.keys(originalData).forEach(function (key) {
currentSeries = {id: key, values: []};
originalData[key].forEach(function (value) {
currentSeries['values'].push({x: value[0], y: value[1]});
});
reshapedData.push(currentSeries);
});

最佳答案

您可以使用 reduce() 方法和内部 map() 方法来创建 values 对象数组。

const data = {"seriesOne":[[1,42.3],[2,12.9]],"seriesTwo":[[1,23.1],[2,10.6]]}
const result = Object.keys(data).reduce((r, id) => {
r.push({id, values: data[id].map(([x, y]) => ({x, y}))})
return r;
}, [])

console.log(result)

关于javascript - d3 数据 reshape : properties to array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50356177/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com