Javascript 从Recharts中的JSON对象打印值?
我有一个JSON输入,列表中的每个项目都有一个评级代码值,如下所示:Javascript 从Recharts中的JSON对象打印值?,javascript,arrays,json,recharts,Javascript,Arrays,Json,Recharts,我有一个JSON输入,列表中的每个项目都有一个评级代码值,如下所示: data = [ { "route": "route1", "rating-code": 2200 }, { "route": "route2", "rating-code": 2600 }, {
data = [
{
"route": "route1",
"rating-code": 2200
},
{
"route": "route2",
"rating-code": 2600
},
{
"route": "route3",
"rating-code": 2600
},
{
"route": "route4",
"rating-code": 2200
},
{
"route": "route5",
"rating-code": 2600
}
];
我正试图制作一个带有记录的条形图,记录X轴上的等级代码和Y轴上的等级代码的路线数。为此,我尝试使用.reduce,得到了预期的输出数组。我现在被困在Recharts的dataKey字段中以绘制这个
我目前的职能:
const newData = data.reduce(function(out, cur) {
let r = cur['rating-code'];
out.codes[r] = (out.codes[r] || 0) + 1;
return out;
},
{'codes':{}});
返回如下内容:
codes: {
1600: 6,
1800: 5,
1900: 1,
2000: 1,
2100: 3,
2200: 1,
2300: 1,
2400: 12,
... }
所以,我想把评级代码作为x轴,对应的数字作为y轴。任何帮助都将不胜感激
<BarChart data={newData ? }>
<XAxis dataKey= ??? />
<YAxis dataKey = ??? />
<Tooltip />
<Legend />
<Bar dataKey = ??? />
</BarChart>
能够通过更改我处理输入路由数据的方式来解决这个问题
const newData = data.reduce(
(acc, el) => {
acc[el['rating-code']] = (acc[el['rating-code']] || 0) + 1;
return acc;
},
{}
);
const codes = Object.entries(newData)
.map(([key, value]) => {
return {ratingCode: key, count: value};
});
这返回了一个适合Recharts格式的数组,如下所示:
[
{ratingCode: "1600", count: 6},
{ratingCode: "1800", count: 5},
{ratingCode: "1900", count: 1},
{ratingCode: "2000", count: 1},
{ratingCode: "2100", count: 3},
etc.
]
最终能够按照预期进行绘图:
<BarChart data={codes}>
<XAxis dataKey="ratingCode" />
<YAxis />
<Tooltip />
<Bar dataKey = "count" />
</BarChart>