parliament parliament - 1 year ago 89
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.

Answer Source

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'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download