Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript underscore array to object

Is there an easy/clean way using Underscore to turn this

[ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ]

Into

 { 'low'    : 9,
   'medium' : 7,
   'high'   : 5 }
like image 726
TheBigC Avatar asked Mar 15 '14 17:03

TheBigC


People also ask

What is underscore in js object?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

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. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

Do we still need Lodash?

But Sometimes You Do Need Lodash Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.


1 Answers

You might consider _.indexBy(...)

var data = [{
    id: 1,
    name: 'Jon Doe',
    birthdate: '1/1/1991',
    height: '5 11'
}, {
    id: 2,
    name: 'Jane Smith',
    birthdate: '1/1/1981',
    height: '5 6'
}, {
    id: 3,
    name: 'Rockin Joe',
    birthdate: '4/4/1994',
    height: '6 1'
}, {
    id: 4,
    name: 'Jane Blane',
    birthdate: '1/1/1971',
    height: '5 9'
}, ];

var transformed = _.indexBy(data, 'id');

Here is a fiddle: https://jsfiddle.net/4vyLtcrf/3/

Update: In Lodash 4.0.1 the method _.indexBy has been renamed to _.keyBy

like image 90
virtualadrian Avatar answered Sep 25 '22 18:09

virtualadrian