parliament parliament - 9 months ago 37
Javascript Question

Underscore.js - Map Array of key/value pairs to an Object - One liner

I've been going through the underscore docs but I can't seem to find a method (or nested method call) to do the following transformation:

Let's say I have the following Javascript array:

[{ "name" : "sEcho", "value" : 1},{ "name" : "iColumns", "value" : 12}, ... ]

And I need to transform it into the following object:

sEcho: 1,
iColumns: 12,

I'm using underscore.js for a reason so it must be a one liner.


Since nobody has posted this as an answer, I'm posting it because I think it is better than Jan's answer. It's shorter, and cleaner without the inline function.

_.object(_.pluck(data, 'name'), _.pluck(data, 'value'));