Last active
February 29, 2024 08:50
-
-
Save naveen-ithappu/c7cd5026f6002131c1fa to your computer and use it in GitHub Desktop.
Converts Array of Objects to HashMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 hasmap | |
* @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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment