簡體   English   中英

在JavaScript中按嵌套數組屬性分組

[英]group by nested array property in JavaScript

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

我不完全確定是否有帶下划線的現成解決方案,但是手動解決此問題也不應該太困難:

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

大概我在打電話

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM