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

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable