Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to flatten this array?

I have this array:

[{name: 'email',value: '[email protected]'}, {name: 'phone',value: '123-123-1234'}]

I need to turn it into this:

{email: '[email protected]', phone: '123-123-1234'}

How can I do this? I figure I can do a million iterators to get the job done, but I think maybe there's a cleaner way to do this.

I'm using Underscore and jQuery if that helps.

like image 566
Will Avatar asked Apr 04 '13 17:04

Will


1 Answers

Array.prototype.reduce is pretty neat for this type of manipulation:

var items = [{name: 'email',value: '[email protected]'}, {name: 'phone',value: '123-123-1234'}]

var data = items.reduce(function (result, item) {
    result[item.name] = item.value;

    return result;
}, {});
like image 110
axelduch Avatar answered Oct 16 '22 05:10

axelduch