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.
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.
The _.each function accepts an array or an object, an iteratee function and an optional context object, the iteratee function is invoked once and in order for each array item The iteratee function provides 3 arguments item - The current iterated object (or value if an object was passed) i - The index of the iterated ...
Introduction to JavaScript Map object An object always has a default key like the prototype. A key of an object must be a string or a symbol, you cannot use an object as a key. An object does not have a property that represents the size of the map.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
For what it's worth, 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');
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