I have array of objects like that
var arr = [
{ id: 4, name: 'John'},
{ id: 7, name: 'Mary'}
];
I want to convert it to object like that
{
4: 'John',
7: 'Mary'
}
There are 4 ways to achieve that
- using
.reduce
: I like the way because.reduce
is used and it is short frequently
_.reduce(arr, function(memo, value) { memo[value.id] = value.name; return memo;}, {});
- using
.map
and.object
: just reference, I don't remember how to use.object
almost
_.chain(arr)
.map(function(value) { return [value.id, value.name];})
.object()
.value();
- using
.pluck
and.object
: just reference, I don't remember how to use.object
almost
_.object(_.pluck(arr, 'id'), _.pluck(arr, 'name'));
- using
.indexBy
and.mapObject
: just reference. It is long
_.chain(arr)
.indexOf('id')
.mapObject(function(value) { return value.name;})
.value();