如何在 js 中对展平数组进行分组

问题描述 投票:0回答:0

对于 javascript 中的扁平化数组

[{
  "category": "FRESH MEAT NON PI",
  "categoryId": 76,
  "subCategoryId": 12,
  "subCategory": "BEEF-THIN MEATS",
  "itemThreshold": null,
  "sellItem": "BEEF SHORT RIBS",
  "sellItemId": 980217310,
  "key": "76-12"
}, {
  "category": "FRESH MEAT NON PI",
  "categoryId": 76,
  "subCategoryId": 12,
  "subCategory": "BEEF-THIN MEATS",
  "itemThreshold": null,
  "sellItem": "BEEF T-BONE STEAK",
  "sellItemId": 12049,
  "key": "76-12"
}]

我们如何在 javascript 中获得如下所示的分组数组

[
  {
    "id": 76,
    "categoryName": "FRESH MEAT NON PI",
    "categoryThreshold": null,
    "subCategories": [
      {
        "id": 10,
        "key": "76-10",
        "name": "BEEF-ROASTS",
        "subCategoryThreshold": null,
        "sellitems": [
          {
            "id": 508,
            "name": "DUMPED ITEM",
            "itemThreshold": 45.0,
            "edited": false,
            "rowId": 1
          },
          {
            "id": 14186,
            "name": "BEEF LOIN TENDERLOIN",
            "itemThreshold": 45.0,
            "edited": false,
            "rowId": 13
          }]
}]
}]

我试过数组reduce方法来制作group

      const out = Object.values(data.reduce((acc, current) => {

      // Destructure the properies from the current object
      const { categoryId, subCategory, ...rest } = current;
    
      
      acc[categoryId] = acc[categoryId] || { categoryId, subCategory: [], ...rest };
    
      
      acc[categoryId].subCategory.push(subCategory);
      
      // Return the accumulator for the next iteration
      return acc;
    }, {}));

如何像我在所需输出中提到的那样,将出售物品作为对象数组添加到对象的子类别数组中。

javascript reactjs arrays lodash
© www.soinside.com 2019 - 2024. All rights reserved.