Snippet so7455119
How to collate an array of dictionaries into a dictionary of arrays?
<!DOCTYPE html>
<!-- http://stackoverflow.com/a/7455119 -->
<html>
<head>
<script type="text/javascript">
var 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 },
];
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);
// map[category].push(list[i]);
}
return map;
}
</script>
</head>
<body>
<script type="text/javascript">
var map = dictionary(list);
for (var cat in map) {
document.write(cat + ": " + map[cat] + "<br />");
}
</script>
</body>
</html>