I have Json Objec
{
"2021": {
"A177": { "Cost": 8828, "year": 2021 },
"A276": { "Cost": 77538, "year": 2021 },
"A188": { "Cost": 8082, "year": 2021 },
},
"2022": {
"A2769": { "Cost": 3916, "year": 2022 },
"A1779": { "Cost": 829, "year": 2022 },
"A2709": { "Cost": 240, "year": 2022 },
}
}
I would like to have:
[
{ "date": '2021', "A177": 8828, "A276": 77538, "A188": 8082},
{ "date": '2022', "A2769": 3916, "A1779": 829, "A2709": 240},
];
how can I do it?
I appreciate your help
CodePudding user response:
You could iterate through all the data's keys (which are the years) and then make an object that contains the year inside the date property along with the keys of the year's data. Best explained with some code:
const data = ...;
let finalized = Object.keys(data).map(k => {
let yearsData = {}; // this is a year's worth of data
for(let l of Object.keys(data[k]))
yearsData[l] = data[k][l]['Cost']; // fill in costs
yearsData['date'] = k; // fill in the date
return yearsData;
});
console.log(finalized);