How to match an array of dictionaries in an array dictionary?

I have this data:

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

And I would like to create a dictionary with a key by category, the value of which is an array containing all the products of this category. My attempt to do this failed:

  var tmp = {};
    list.forEach(function(product) {
      var idx = product.category ;
      push tmp[idx], product;
    });
    tmp;
+5
source share
1 answer
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

You can check it out on jsfiddle .

+5
source

All Articles