有人可以帮助我将此数组展平为所需格式吗?我不知道。我需要父键的名称为“ type”,子父键的名称为“ category”。
最好将其美化,以便更好地查看格式。似乎在这里无法做到...
[{
"Labour": {
"Cleaners": {
"unitCost": 3409.5,
"markupValue": 18,
"totalCost": 3643.5
},
"Plumber": {
"unitCost": 309.0909,
"markupValue": 0,
"totalCost": 309.0909
}
}
},
{
"Material": {
"Cleaners": {
"unitCost": 450,
"markupValue": 5,
"totalCost": 475
},
"Plumber": {
"unitCost": 450,
"markupValue": 5,
"totalCost": 475
}
}
},
{
"Other": {
"Report Fee": {
"unitCost": 180,
"markupValue": 0,
"totalCost": 180
}
}
}
]
[{
"type": "Labour",
"category": "Cleaners",
"unitCost": 3409.5,
"markupValue": 18,
"totalCost": 3643.5
},
{
"type": "Labour",
"category": "Plumbers",
"unitCost": 3409.5,
"markupValue": 18,
"totalCost": 3643.5
},
{
"type": "Material",
"category": "Cleaners",
"unitCost": 450.5,
"markupValue": 0,
"totalCost": 5
},
{
"type": "Material",
"category": "Plumbers",
"unitCost": 450.5,
"markupValue": 0,
"totalCost": 5
}
]
答案 0 :(得分:1)
使用Array.prototype.flatMap()
和Array.prototype.flat()
函数,可以将多维数组转换为1d数组,如下所示。
const input = [
{
"Labour": {
"Cleaners": {
"unitCost": 3409.5,
"markupValue": 18,
"totalCost": 3643.5
},
"Plumber": {
"unitCost": 309.0909,
"markupValue": 0,
"totalCost": 309.0909
}
}
},
{
"Material": {
"Cleaners": {
"unitCost": 450,
"markupValue": 5,
"totalCost": 475
},
"Plumber": {
"unitCost": 450,
"markupValue": 5,
"totalCost": 475
}
}
},
{
"Other": {
"Report Fee": {
"unitCost": 180,
"markupValue": 0,
"totalCost": 180
}
}
}
];
const output = input.flatMap((item) => {
return Object.entries(item).map(([type, value]) => (Object.entries(value)
.map(([category, subValue]) => ({
type,
category,
...subValue
}))
));
}).flat();
console.log(output);