[英]Convert nested array of objects to specific group of objects of the data in JavaScript or TypeScript
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?我如何迭代和更改整个 object 如果我确实有很多数据,这是支持更少迭代的最佳方法?
try this, and see if work.试试这个,看看是否有效。 you can condense the code into one function if you want to.
如果需要,您可以将代码压缩为一个 function。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.