I am using the excellent Underscore.js library. I have a specific task which I can do fine using JavaScript or jQuery but was wondering if there was some sort of abstraction avaialable in Underscore that I was missing out on.
Essentially I have an object like so -
var some_object_array = [{id: "a", val: 55}, {id: "b", val: 1}, {id: "c", val: 45}];
I want to convert this into -
var some_map = {"a": {id: "a", val: 55}, "b": {id: "b", val: 1}, "c": {id: "c", val: 45}};
I know that I can use _.groupBy(some_object_array, "id")
. But this returns a map like so -
var some_grouped_map = {"a": [{id: "a", val: 55}], "b": [{id: "b", val: 1}], "c": [{id: "c", val: 45}]};
Note that this does what it is advertised to do. But I was hoping to get some_map
without iterating over the objects myself.
Any help appreciated.
FWIW since underscore.js you can now use _.object()
var some_map = _.object(_.map(some_object_array, function(item) {
return [item.id, item]
}));
for your case, you should use the indexBy
function:
var some_object_array = [{id: "a", val: 55}, {id: "b", val: 1}, {id: "c", val: 45}];
var some_grouped_map = _.indexBy(some_object_array, 'id');
There is also this method
_.reduce(data, function (o, item) { o[item.key] = item.value; return o }, {})
Which is one statement with two statements in the inner function.
I don't think there's something closer than groupBy for your needs. Even if there was, it wouldn't do better than a simple:
var some_map = {};
_.each(some_object_array, function(val) {
some_map[val.id] = val;
});
I this case you don't need to iterate the array. Not map
, not reduce
, not transform
. All you need is the old pluck
_.object(_.pluck(some_object_array, 'id'), some_object_array);
for ES6, it's
var some_map = _.chain(some_object_array)
.map(item => [item.id, item])
.object()
.value()
I solved this way, using lodash:
const ar = [
{ key: '1', val: 'a' },
{ key: '2', val: 'b' },
{ key: '3', val: 'c' }
]
const obj = _.keyBy({ ...ar }, 'key')
console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>