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 }
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.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With