I want to sum up and flatten the structure of an API response. Since I didn't succeed by iterating over the key/value pairs of input.statistic I came up with another solution which does the job but I'm not happy with it.
What I do recieve is:
input = {
"data": some unimportant stuff,
"statistic": [
{
"valueId": 111,
"statistic": {
"min": 0,
"max": 0,
"average": 0.12
}
},
{
"valueId": 222,
"statistic": {
"min": 0,
"max": 1,
"average": 0.14
}
}
]
}
At this point I'm only interested in the statistic data and I want to change it to something like that:
{
"stat111": [
{name: "min", value: 0},
{name: "max", value: 0},
{name: "average", value: 0.12}
],
"stat222": [
{name: "min", value: 0},
{name: "max", value: 1},
{name: "average", value: 0.14}
]
}
What I do is:
const statDat = {};
for (const item of input.statistic) {
const nameTop = 'stat' + item.valueId.toString();
const props = [];
for (let key in item.statistic) {
props.push({name: key, value: item.statistic[key]});
}
statDat[nameTop] = props;
}
So statDat looks the way I want it but once more I'm sure that there is a better and newer way of flatten and renaming the structure. Any hints?