用例是对象的数组基于字符串或提供给评价函数和使用转换成一个散列映射作为散列表和值作为对象本身的关键。使用它的常见情况是将对象数组转换为对象的哈希映射。
代码
以下是在javascript一小段转换对象数组散列地图,由对象的属性值索引。您可以提供一个函数来动态评估哈希映射的关键(运行时间)。希望这有助于未来的任何人。
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;
};
您可以在这里找到要点:https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa
你应该在问题本身包含任何相关的代码。 – jmar777 2014-10-08 19:34:54
这里有什么问题? – 2017-06-18 00:01:59