我正在努力為我的圖表創建正確的資料模板。我希望它用實際月份創建過去 12 個月的模板。例如,如果我想擁有過去 12 個月的資料,我應該擁有如下所示的資料模板:
[{id: BAD,
data: [
{
x: "11",
y: 0
},
{
x: "12",
y: 0
},
{
x: "1",
y: 0
},
...
]},
{id: GOOD,
data: [
{
x: "11",
y: 0
},
{
x: "12",
y: 0
},
{
x: "1",
y: 0
},
...
]},
...
]
這不是那么簡單,因為我不知道當月份增加到 12 時該怎么做,因為它只是不斷增加代表月份的“x”的值,因此我不知道我應該如何實作它。
我試圖做的就是這個。我沒有其他線索如何得到這個任何提示我怎么能得到那個?
const NUMBER_OF_MONTHS = 12;
const getFirstMonth = (date, numOfMonths) => {
date.setMonth(date.getMonth() - numOfMonths);
return date.getMonth();
}
const createDataTemplate = () => {
const template = [];
const firstMonth = getFirstMonth(new Date(), NUMBER_OF_MONTHS)
for (let i = 0; i < RATINGS.length; i ) {
template.push({
'id': RATINGS[i],
'data': []
})
for (let j = 1; j <= NUMBER_OF_MONTHS; j ) {
template[i].data.push({
'x': `${firstMonth j}`,
'y': 0
})
}
}
return template;
}
uj5u.com熱心網友回復:
我這樣解決了,生成了未來 12 個月/年的陣列。然后你可以用它來回圈并添加到你data
const NUMBER_OF_MONTHS = 12;
const getNextTwelveMonths = () => {
const currentMonth = new Date().getMonth();
// create array with the months until the currentMonth
const months = new Array(currentMonth).fill(null).map((_, i) => i 1);
// add the last x months to the begin of the array
for (let i = NUMBER_OF_MONTHS; i > currentMonth; i--) {
months.unshift(i);
}
return months;
};
const createDataTemplate = () => {
const template = [];
for (let i = 0; i < RATINGS.length; i ) {
template.push({
id: RATINGS[i],
data: [],
});
const nextMonths = getNextTwelveMonths();
for (let j = 0; j < nextMonths.length; j ) {
template[i].data.push({
x: `${nextMonths[j]}`,
y: 0,
});
}
}
return template;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535837.html
標籤:javascript反应
下一篇:如何合并三個html元素
