如何通过数组中嵌套的数组子对象对对象进行分组

时间:2020-04-04 19:47:07

标签: javascript arrays underscore.js lodash

我遇到了一个小问题,试图将它扫到地毯下。

我正在调用的是产品API,每个产品都有一个键categories,其键值为地图数组的值。尝试按类别对这些分类。

这是我来自API的示例响应

[
  {
    "name": "Product one",
    "categories": [
      {
        "id": 1,
        "name": "Category One"
      }
    ]
  },
  {
    "name": "Product Two",
    "categories": [
      {
        "id": 1,
        "name": "Category One"
      },
      {
        "id": 2,
        "name": "Category two"
      }
    ]
  }
]

我编写的代码如下:

 function groupBy(arr) {
      let categories = [];
      arr.forEach(el => {
        el.categories.forEach(c => {
          // Skapa ny kategori om inte redan existerar
          if (!categories.includes(c.id)) {
            categories.push({
              name: c.name,
              id: c.id,
              products: [el]
            });
          } else {
            // Lägg till produkt i existerande kategori
            categories.forEach(_c => {
              if (_c.id === c.id) {
                _c.products.push(el)
              }
            })
          }
        });
      });

      return categories;
    }

groupBy(arr);

我认为我在某种程度上过度使用它,期望的结果当然是没有任何重复的类别,产品应放入products[]中。

Screenshot of console output in Chrome browser

2 个答案:

答案 0 :(得分:2)

可以使用map-reduce

const data = [{"name":"Product one","categories":[{"id":1,"name":"Category One"}]},{"name":"Product Two","categories":[{"id":1,"name":"Category One"},{"id":2,"name":"Category two"}]}];

function categoriesList(list = []) {
  return Object.values(
    list.reduce((arr, product) => {
      product.categories.forEach((cat) => {
        if (!arr[cat.id]) arr[cat.id] = { ...cat, products: [] };
        arr[cat.id].products.push(product);
      });
      return arr;
    }, {})
  );
}
console.log(JSON.stringify(categoriesList(data), null, 4));
.as-console {
  min-height: 100% !important;
}

.as-console-row {
  color: blue !important;
}

答案 1 :(得分:1)

您可以通过首先迭代产品以将其分配给每个类别来实现。为了防止重复,您想使用一个映射或集合;在这里,我使用一个javascript对象作为地图。一旦有了,就可以通过使用地图对象上的Object.values()将其转换为所需的数组

const groupProductsByCategory = (products) => {
  // reduce down each product into a category map
  const productsGroupedByCategory = products.reduce((categories, product) => {
    // insert the current product into each of the categories it contains
    product.categories.forEach(category => {
      // if the category exists in the map, we just need to append the current product
      if (category.id in categories)
        categories[category.id].products.push(product)
      else // otherwise, create a new category object with the current product
      categories[category.id] = ({ ...category, products: [product] })
    })
    return categories
  }, ({}))

  // convert the object into an array of objects
  return Object.values(productsGroupedByCategory)
}