What I've got is array of objects
const incomeRows = [
{
group: "Deck 1",
categories: [
{ category: "Deck Supplies", reportvalue: 100, transdate: "2020-11" },
{ category: "Deck Supplies", reportvalue: 200, transdate: "2020-11" },
{ category: "Deck Contractors", reportvalue: 300, transdate: "2020-11" },
{ category: "Deck Contractors", reportvalue: 400, transdate: "2020-12" },
{ category: "Deck Contractors", reportvalue: 500, transdate: "2020-12" }
]
},
{
group: "Deck 2",
categories: [
{ category: "Deck Supplies", reportvalue: 10, transdate: "2020-11" },
{ category: "Deck Supplies", reportvalue: 20, transdate: "2020-11" },
{ category: "Deck Contractors", reportvalue: 30, transdate: "2020-11" },
{ category: "Deck Contractors", reportvalue: 40, transdate: "2020-12" },
{ category: "Deck Contractors", reportvalue: 50, transdate: "2020-12" }
]
}
];
What I need to create is:
const finalOutput = [
{
group: "Deck 1",
categories: [
{
category: "Deck Supplies",
"2020-11": 300
},
{
category: "Deck Contractors",
"2020-11": 300,
"2020-12": 900
}
],
groupMonthlyIncomes: {
"2020-11": 600,
"2020-12": 900
}
},
{
group: "Deck 2",
categories: [
{
category: "Deck Supplies",
"2020-11": 30
},
{
category: "Deck Contractors",
"2020-11": 30,
"2020-12": 90
}
],
groupMonthlyIncomes: {
"2020-11": 60,
"2020-12": 90
}
}
];
So the category is unique and it has total values for each month like "2020-11": 300
and each group has its total monthly values like
groupMonthlyIncomes: {
"2020-11": 60,
"2020-12": 90
}
What I've done so far is:
let formatedRows = incomeRows.map(el => (
{
group: el.group,
categories: []
}
));
let formatedCategories = incomeRows.map(el => (
el.categories.map(cat => {
return {
category: cat.category,
[cat.transdate.toString()]: cat.reportvalue
}
})
));
Can anybody let me know what should be the next step or point me into any other solution if there is a better way to do it?