用例
用例是根据提供的字符串或函数将对象数组转换为散列映射,以计算并用作散列映射中的键,并将值用作对象本身。使用这种方法的一种常见情况是将对象数组转换为对象的散列映射。
代码
以下是JavaScript中的一小段代码,用于将对象数组转换为散列映射,该映射由对象的属性值索引。您可以提供一个函数来动态(运行时)评估hash map的键值。
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;
};你可以在这里找到要点:Converts Array of Objects to HashMap。
发布于 2014-10-09 03:41:59
这对于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' }
注意:Array.prototype.reduce()是IE9+,所以如果你需要支持老的浏览器,你需要多填充它。
发布于 2016-07-28 04:07:45
使用ES6 Map (pretty well supported),您可以尝试执行以下操作:
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"}
发布于 2019-07-19 21:17:15
您可以使用新的Object.fromEntries()方法。
示例:
const array = [
{key: 'a', value: 'b', redundant: 'aaa'},
{key: 'x', value: 'y', redundant: 'zzz'}
]
const hash = Object.fromEntries(
array.map(e => [e.key, e.value])
)
console.log(hash) // {a: b, x: y}
https://stackoverflow.com/questions/26264956
复制相似问题