gpt4 book ai didi

javascript - Chart.js 中带有 JSON 数据的堆叠条形图

转载 作者:行者123 更新时间:2023-12-01 04:03:27 25 4
gpt4 key购买 nike

我有以下 JSON 数据。

[
{
"date": "2016-05-01T00:00:00",
"productInformation": [
{
"productName": "Apple",
"totalWeight": 200
}
]
},
{
"date": "2016-09-01T00:00:00",
"productInformation": [
{
"productName": "Apple",
"totalWeight": 632
},
{
"productName": "Mango",
"totalWeight": 856
},
{
"productName": "Spinach",
"totalWeight": 545
},
{
"productName": "Grapes",
"totalWeight": 338
}
]
},
{
"date": "2017-01-01T00:00:00",
"productInformation": [
{
"productName": "Mango",
"totalWeight": 500
}
]
}
]

在 X 轴上我想显示月份和年份,在 Y 轴上我想显示产品信息的堆叠栏。例如,在 2016-05 中只有 Apple,因此它只会显示 apple。 2016-09年有4个产品,因此将根据4个产品及其总重量显示4个质押条。我已阅读 Chart.js 文档。根据文档,我必须在数据集中提供 Y 轴值。如何提取数据集的 Y 轴值以从给定的 JSON 数据创建堆叠条形图?如果我想根据上面给出的 JSON 数据手动创建图表,那么它会是这样的。

var barChartData = {
labels: ["May 2016", "September 2016", "January 2017"],
datasets: [{
label: "Apple",
data: [200, 632, 0],
backgroundColor: "#3c8dbc"
},
{
label: "Mango",
data: [0,856,500],
backgroundColor: "#3c8dbc"
},
{
label: "Spinach",
data: [0,545,0],
backgroundColor: "#3c8dbc"
},
{
label: "Grapes",
data: [0,338,0],
backgroundColor: "#3c8dbc"
}]
};

我需要一种方法从给定的 JSON 数据中提取数据集的 data 部分。

最佳答案

这段代码应该可以解决您问题中最难的部分(使用 ES6 语法):

const data = [{
"date": "2016-05-01T00:00:00",
"productInformation": [{
"productName": "Apple",
"totalWeight": 200
}]
}, {
"date": "2016-09-01T00:00:00",
"productInformation": [{
"productName": "Apple",
"totalWeight": 632
}, {
"productName": "Mango",
"totalWeight": 856
}, {
"productName": "Spinach",
"totalWeight": 545
}, {
"productName": "Grapes",
"totalWeight": 338
}]
}, {
"date": "2017-01-01T00:00:00",
"productInformation": [{
"productName": "Mango",
"totalWeight": 500
}]
}]

const uniq = a => [...new Set(a)]
const flatten = a => [].concat.apply([], a)

// step 1: find the distinct dates: ["2016-05-01T00:00:00", ... ]
const dates = data.map(e => e.date)

// step 2: find the distinct labels: [Apple, Mango, ... ]
const labels = uniq(
flatten(data.map(e => e.productInformation))
.map(e => e.productName))

// step 3: map the labels to entries containing their data by searching the original data array
const result = labels.map(label => {
return {
label,
data: dates.map(date => {
const hit = data.find(e => e.date === date)
.productInformation
.find(p => p.productName === label)
return hit ? hit.totalWeight : 0
})
}
})

console.log(result)

关于javascript - Chart.js 中带有 JSON 数据的堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001984/

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