Fetching the Data
In this step, you will learn how to fetch the data from the data.json
file and store it in the necessary data structures.
- Open the
index.html
file in your code editor.
- Locate the
// TODO
section in the JavaScript code.
- Create two objects to store the weekly and monthly data:
// TODO
let weekData = {
x: [],
y: []
};
let monthData = {
x: [],
y: []
};
- Implement the
mySetOption()
function to update the chart's options based on the data passed to it.
function mySetOption(data) {
option.xAxis.data = data.x;
option.series[0].data = data.y;
myChart.setOption(option);
}
- Use the
axios.get()
method to fetch the data from the data.json
file. The response from the API call will contain the data in the res.data.data
property.
axios.get("./data.json").then((res) => {
const data = res.data.data;
// Process the data here
});
- Inside the callback function of the
then()
method, iterate through the data
object and process the study duration data for each day. Calculate the total study duration for each week and month, and store the results in the weekData
and monthData
objects, respectively.
for (const key in data) {
let weekCount = (monthCount = 0),
weekNum = 1;
for (let i = 0; i < data[key].length; i++) {
weekCount += data[key][i];
monthCount += data[key][i];
if (
(i + 1) % 7 === 0 ||
(data[key].length - i <= 7 && i === data[key].length - 1)
) {
weekData.x.push(`Week ${weekNum++} (${key})`);
weekData.y.push(weekCount);
weekCount = 0;
}
}
monthData.x.push(key);
monthData.y.push(monthCount);
}
- After processing the data, call the
mySetOption()
function and pass the weekData
object to display the weekly statistics by default.
mySetOption(weekData);
- The effect of the code after this step of processing is as follows:
// TODO
let weekData = {
x: [],
y: []
},
monthData = {
x: [],
y: []
};
function mySetOption(data) {
option.xAxis.data = data.x;
option.series[0].data = data.y;
// reset
myChart.setOption(option);
}
axios.get("./data.json").then((res) => {
const data = res.data.data;
for (const key in data) {
let weekCount = (monthCount = 0),
weekNum = 1;
for (let i = 0; i < data[key].length; i++) {
weekCount += data[key][i];
monthCount += data[key][i];
if (
(i + 1) % 7 === 0 ||
(data[key].length - i <= 7 && i === data[key].length - 1)
) {
weekData.x.push(`Week ${weekNum++} (${key})`);
weekData.y.push(weekCount);
weekCount = 0;
}
}
monthData.x.push(key);
monthData.y.push(monthCount);
}
mySetOption(weekData);
});