{
"data": {
"success": true,
"timeseries": true,
"start_date": "2022-02-01",
"end_date": "2022-03-02",
"base": "RUB",
"rates": {
"2022-02-01": {
"USD": 0.012922641020611143
},
"2022-02-02": {
"USD": 0.013024953827785636
},
"2022-02-03": {
"USD": 0.013111232627449121
},
"2022-02-04": {
"USD": 0.013080360583812869
}
}
}
}
Above is the JSON that is returned from my axios query. I've tried to use a loop and forEach to capture the date and USD value for an x,y of a chart but I can't seem to get both of them at the same time. Below is my chart code so far.
function fnChart04() {
var chartArray = [];
var yesterday = moment().subtract(24, 'hours').format('YYYY-MM-DD');
var url = "https://commodities-api.com/api/timeseries?access_key=XYZed&start_date=2022-02-01&end_date=" yesterday "&base=RUB&symbols=USD";
var header = { headers: {'Accept': 'application/json; odata=nometadata'} };
axios.get(url, header).then(function (response) {
var results = response.data;
let rate = results.data.rates.USD;
let date = results.data.rates[0];
//issue is here - I cannot figure out how to loop through rates to separate the date and the USD value to add to the chartArray.
chartArray.push({x: date, y: rate});
new Chart(document.getElementById("myChart04"), {
type: 'line',
data: {
labels: chartArray.map(function(a) { return a.x; }),
datasets: [{
data: chartArray,
label: "RUB | USD",
borderColor: "#f93154",
backgroundColor: "#fee3e8",
fill: true
}]
},
options: {
response: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
});
}
Any advice on how to do this would be really appreciated. I know I'm missing something simple.
CodePudding user response:
You can loop through the keys of rates
using Object.keys
and then push to the chartArray
let results = {
"data": {
"success": true,
"timeseries": true,
"start_date": "2022-02-01",
"end_date": "2022-03-02",
"base": "RUB",
"rates": {
"2022-02-01": {
"USD": 0.012922641020611143
},
"2022-02-02": {
"USD": 0.013024953827785636
},
"2022-02-03": {
"USD": 0.013111232627449121
},
"2022-02-04": {
"USD": 0.013080360583812869
}
}
}
}
let chartArray = [];
Object.keys(results.data.rates).forEach((key) => chartArray.push({x: key,y: results.data.rates[key]["USD"]}))
console.log(chartArray)