Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  33] [ 1]  / answers: 1 / hits: 15329  / 13 Years ago, sat, september 17, 2011, 12:00:00

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;

More From » javascript

 Answers
14
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.


[#90047] Thursday, September 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dallasb

Total Points: 657
Total Questions: 98
Total Answers: 97

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;