2011-09-17 91 views
5

我有這樣的數據:如何將字典數組整理成數組字典?

list = [ 
     {name:'apple', category: "fruit", price: 1.22 }, 
     {name:'pear', category: "fruit", price: 2.22 }, 
     {name:'coke', category: "drink", price: 3.33 }, 
    {name:'sprite', category: "drink", price: .44 }, 
    ]; 

而且我想創建鍵安裝在A類字典,它的值是一個包含該類別的所有產品的數組。我試圖這樣做失敗:

var tmp = {}; 
    list.forEach(function(product) { 
     var idx = product.category ; 
     push tmp[idx], product; 
    }); 
    tmp; 
+2

'push tmp [idx],product;'是無效的JavaScript,難怪它失敗了。 –

回答

5
function dictionary(list) { 
    var map = {}; 
    for (var i = 0; i < list.length; ++i) { 
     var category = list[i].category; 
     if (!map[category]) 
      map[category] = []; 
     map[category].push(list[i].name); // add product names only 
     // map[category].push(list[i]); // add complete products 
    } 
    return map; 
} 
var d = dictionary(list); // call 

您可以測試它jsfiddle