按 JavaScript 中的嵌套数组 属性 分组

group by nested array property in JavaScript

我的 Web 应用程序中有一个 json 对象,如下所示。它是一个产品对象数组,每个产品对象都有一个类别 属性,其中包含产品所属的一组类别。

var products = [  
   {  
      "id":1,
      "name":"Product 1",
      "price":10,
      "category":[  
         {  
            "id":10,
            "name":"Category 1"
         },
         {  
            "id":20,
            "name":"Category 2"
         }
      ]
   },
   {  
      "id":2,
      "name":"Product 2",
      "price":20,
      "category":[  
         {  
            "id":20,
            "name":"Category 2"
         },
         {  
            "id":30,
            "name":"Category 3"
         }
      ]
   }
]

所以现在我想按类别分组显示它们,这样最终结果将如下所示。我已经在我的项目中使用了Underscore.js,所以如果我能用它来实现这一点就好了。

var categories = [  
   {  
      "id":10,
      "name":"Category 1",
      "products":[  
         {  
            "id":1,
            "name":"Product 1",
            "price":10
         }
      ]
   },
   {  
      "id":20,
      "name":"Category 2",
      "products":[  
         {  
            "id":1,
            "name":"Product 1",
            "price":10
         }, 
         {
            "id":2,
            "name":"Product 2",
            "price":20,
         }
      ]
   },
   {  
      "id":30,
      "name":"Category 3",
      "products":[  
         {  
            "id":2,
            "name":"Product 2",
            "price":20,
         }
      ]
   }
]

我不完全确定是否有现成的解决方案来解决这个带下划线的问题,但是手动解决这个问题应该不会太难,或者:

var categoriesIndexed = {};
var categories = [];

products.forEach(function(product) {
    product.category.forEach(function(category) {
        // create a new category if it does not exist yet
        if(!categoriesIndexed[category.id]) {
            categoriesIndexed[category.id] = {
                id: category.id,
                name: category.name,
                products: []
            };
            categories.push(categoriesIndexed[category.id]);
        }

        // add the product to the category
        categoriesIndexed[category.id].products.push({
            id: product.id,
            name: product.name,
            price: product.price   
        });
    });
});

这是我会做的

var categories = [];
var cat = new Map();

var addUniqueCategory(category) { /* determine if category is already in list of categories, if not add it to categories */ };

products.each (function (item) {
     item.categories.each(function (c) {
         if (!cat.has(c.name)) cat.set(c.name, []);

         var list = cat.get(c.name);
         list.push( { id: item.id, name: item.name, price: item.price });

         addUniqueCategory(c);
     });
});

categories.each( function (c) {
    var list = cat.get(c.name);
    if (!c.products) c.products = [];
    c.products.splice( c.length, 0, list);
 });

大致上,我在 phone