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

时间:2016-06-20 23:17:01

标签: javascript underscore.js

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

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,
         }
      ]
   }
]

2 个答案:

答案 0 :(得分:2)

我不完全确定使用下划线是否有解决此问题的开箱即用解决方案,但是手动解决这个问题也不应该太难:

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   
        });
    });
});

答案 1 :(得分:2)

这就是我要做的事情

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);
 });

粗略地说,我正在打电话