Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 980
parliament Avatar asked Jul 23 '13 05:07

parliament


People also ask

What is _ in Map JavaScript?

The _. js library of the JavaScript which is used to produce a new array of values by mapping each value in list through transformation function (iteratee). It displays the result as a list on the console.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


1 Answers

Variation on Sza's answer, using the "array of pairs" signature of _.object:

_.object(_.map(data, function(x){return [x.name, x.value]})) 
like image 150
John Dvorak Avatar answered Sep 23 '22 23:09

John Dvorak