Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object array to hash map, indexed by an attribute value of the Object

Use Case

The use case is to convert an array of objects into a hash map based on string or function provided to evaluate and use as the key in the hash map and value as an object itself. A common case of using this is converting an array of objects into a hash map of objects.

Code

The following is a small snippet in JavaScript to convert an array of objects to a hash map, indexed by the attribute value of object. You can provide a function to evaluate the key of hash map dynamically (run time).

function isFunction(func) {     return Object.prototype.toString.call(func) === '[object Function]'; }  /**  * This function converts an array to hash map  * @param {String | function} key describes the key to be evaluated in each object to use as key for hashmap  * @returns Object  * @Example   *      [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap("id")  *      Returns :- Object {123: Object, 345: Object}  *  *      [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap(function(obj){return obj.id+1})  *      Returns :- Object {124: Object, 346: Object}  */ Array.prototype.toHashMap = function(key) {     var _hashMap = {}, getKey = isFunction(key)?key: function(_obj){return _obj[key];};     this.forEach(function (obj){         _hashMap[getKey(obj)] = obj;     });     return _hashMap; }; 

You can find the gist here: Converts Array of Objects to HashMap.

like image 254
Naveen I Avatar asked Oct 08 '14 19:10

Naveen I


People also ask

How do you turn an array of objects into a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

How do you map data from an array of objects in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

How do I convert an object to a map in typescript?

To convert an object to a Map , call the Object. entries() method to get an array of key-value pairs and pass the result to the Map() constructor, e.g. const map = new Map(Object. entries(obj)) . The new Map will contain all of the object's key-value pairs.

What is map in JavaScript with example?

Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.


2 Answers

This is fairly trivial to do with Array.prototype.reduce:

var arr = [      { key: 'foo', val: 'bar' },      { key: 'hello', val: 'world' }  ];    var result = arr.reduce(function(map, obj) {      map[obj.key] = obj.val;      return map;  }, {});    console.log(result);  // { foo:'bar', hello:'world' }

Note: Array.prototype.reduce() is IE9+, so if you need to support older browsers you will need to polyfill it.

like image 114
jmar777 Avatar answered Sep 29 '22 12:09

jmar777


Using ES6 Map (pretty well supported), you can try this:

var arr = [      { key: 'foo', val: 'bar' },      { key: 'hello', val: 'world' }  ];    var result = new Map(arr.map(i => [i.key, i.val]));    // When using TypeScript, need to specify type:  // var result = arr.map((i): [string, string] => [i.key, i.val])    // Unfortunately maps don't stringify well.  This is the contents in array form.  console.log("Result is: " + JSON.stringify([...result]));   // Map {"foo" => "bar", "hello" => "world"}
like image 41
mateuscb Avatar answered Sep 29 '22 13:09

mateuscb