Creating An Associative Array In JavaScript Using The Map Function
Answer :
You may use Array.prototype.reduce
for your task. It allows a return value in the callback function for the next call.
var data = [
{ 'list': 'one', 'item': 1 },
{ 'list': 'one', 'item': 2 },
{ 'list': 'one', 'item': 3 },
{ 'list': 'two', 'item': 1 },
{ 'list': 'two', 'item': 2 }
],
flat = data.reduce(function (r, a) {
r[a.list] = r[a.list] || [];
r[a.list].push(a.item);
return r;
}, {});
document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');
Comments
Post a Comment