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

Published: 09 April 2024
on channel: Code Samples
13
2

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.
Array.prototype.reduce: https://developer.mozilla.org/en-US/d...


Watch video javascript - Convert object array to hash map, indexed by an attribute value of the Object online without registration, duration hours minute second in high quality. This video was added by user Code Samples 09 April 2024, don't forget to share it with your friends and acquaintances, it has been viewed on our site 13 once and liked it 2 people.