Reputation: 113
I am having a double nested array of objects and I would like to change to a specific array of groups to support my table structure.
Below are my objects and the result I am expecting.
let newData = {
data: {
summary: [
{
code: "12",
data: [
{
group: "Trade",
currency: "CAD", //group1
amount: "$3,443.00",
total: 1
},
{
group: "Trade",
currency: "USD", //group2
amount: "$0.00",
total: 0
},
{
group: "Commission",
currency: "CAD", //group3
amount: "$0.00",
total: 0
},
{
group: "Commission",
currency: "USD", //group4
amount: "$0.00",
total: 0
}
]
},
{
code: "34",
data: [
{
group: "Trade",
currency: "CAD", //group1
amount: "$343.00",
total: 21
},
{
group: "Trade",
currency: "USD", //group2
amount: "$40.00",
total: 40
},
{
group: "Commission",
currency: "CAD", //group3
amount: "$30.00",
total: 30
},
{
group: "Commission",
currency: "USD", //group4
amount: "$20.00",
total: 20
}
]
}
]
}
};
let result = [
{
code: "12",
TradeCAD:
{
group: "Trade",
currency: "CAD", //group1
amount: "$3,443.00",
total: 1
},
TradeUSD:
{
group: "Trade",
currency: "USD", //group2
amount: "$0.00",
total: 0
},
CommissionCAD: {
group: "Commission",
currency: "CAD", //group3
amount: "$0.00",
total: 0
},
CommissionUSD: {
group: "Commission",
currency: "USD", //group4
amount: "$0.00",
total: 0
}
},
{
code: "34",
TradeCAD:
{
group: "Trade",
currency: "CAD", //group1
amount: "$343.00",
total: 21
},
TradeUSD:
{
group: "Trade",
currency: "USD", //group2
amount: "$40.00",
total: 40
},
CommissionCAD: {
group: "Commission",
currency: "CAD", //group3
amount: "$30.00",
total: 30
},
CommissionUSD: {
group: "Commission",
currency: "USD", //group4
amount: "$20.00",
total: 20
}
},
];
How I can iterate and change the whole object and If I do have a lot of data which is the best approach to follow to support fewer iterations?
Upvotes: 1
Views: 88
Reputation: 4592
try this, and see if work. you can condense the code into one function if you want to.
const result = newData.data.summary.map(item => {
const res = {
code: item.code,
}
item.data.forEach(d => {
res[`${d.group}${d.currency}`] = d;
d.amount = d.amount || "$0.00"; // default value for amount
d.total = d.total || 0; // default value for total
})
return res;
});
console.log(JSON.stringify(result));
Upvotes: 2