'Build a dataset from api response
I have this :
{
"2018-12": 1778
"2018-11": 3190
"2018-10": 5318
"2018-09": 2498
"2018-08": -2791
"2018-07": 1710
"2018-06": 1786
"2019-12": 3513.97
"2019-11": 2975.9700000000003
"2019-10": -5407.53
"2019-09": 5188.02
"2019-08": 5599.2699999999995
"2019-07": 3930.37
"2019-06": 1434.95
"2019-05": 4834.02
"2019-04": 2479.5299999999997
"2019-03": 6247.06
"2019-02": 2066.4
"2019-01": 2073.8799999999997
"2020-12": 1092.79
}
My code is :
let data = (new Array(12)).fill(null);
const datasets = [];
const colors = ['#4A90E270', '#27AE6070', '#F7981C70', '#47381C70'];
let colorIndex = 0;
Object.entries(inputObject).forEach(([key, value]) => {
const [year, month] = key.split('-');
const foundElement = datasets.some((el) => el.label === year.toString());
if (!foundElement) {
datasets.push({
data,
label: year.toString(),
borderColor: colors[colorIndex],
fill: false,
lineTension: 0,
});
colorIndex += 1;
data = (new Array(12)).fill(null);
}
data[parseInt(month, 10) - 1] = parseFloat(value).toFixed(1);
});
But is not working as expected. Because I want to get all values by year, for example put all data for year 2018 in data, after data reset data and put for year 2019 all data. How can I resolve this? Now like is done is not working properly.
Solution 1:[1]
I'm not sure to understand what's your expected result.
If you need to push all your data in a object by year, then you need to iterate your data by keys and then push your value to the year key .
const data = {
"2018-12": 1778,
"2018-11": 3190,
"2018-10": 5318,
"2018-09": 2498,
"2018-08": -2791,
"2018-07": 1710,
"2018-06": 1786,
"2019-12": 3513.97,
"2019-11": 2975.9700000000003,
"2019-10": -5407.53,
"2019-09": 5188.02,
"2019-08": 5599.2699999999995,
"2019-07": 3930.37,
"2019-06": 1434.95,
"2019-05": 4834.02,
"2019-04": 2479.5299999999997,
"2019-03": 6247.06,
"2019-02": 2066.4,
"2019-01": 2073.8799999999997,
"2020-12": 1092.79,
}
let result = {}
Object.keys(data).forEach(date => {
const year = date.split("-")[0]
if(!result[year]){
result[year]=[data[date]]
}
else{
result[year].push(data[date])
}
})
console.log(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexis |
