将具有索引的数组展平为具有类型的对象

时间:2020-11-06 02:01:50

标签: javascript arrays

有人可以帮助我将此数组展平为所需格式吗?我不知道。我需要父键的名称为“ 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
  }
]

1 个答案:

答案 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);

相关问题