Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to collate an array of dictionaries into a dictionary of arrays?

Tags:

javascript

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'd like to create a dictionary keyed on category, whose value is an array that contains all the products of that category. My attempt to do this failed:

  var tmp = {};
    list.forEach(function(product) {
      var idx = product.category ;
      push tmp[idx], product;
    });
    tmp;
like image 359
Terrence Brannon Avatar asked Sep 17 '11 13:09

Terrence Brannon


1 Answers

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 test it on jsfiddle.

like image 134
Jiri Kriz Avatar answered Sep 28 '22 06:09

Jiri Kriz