2014-10-08 86 views
79

使用案例转换对象阵列散列映射,由对象的属性值索引的

用例是对象的数组基于字符串或提供给评价函数和使用转换成一个散列映射作为散列表和值作为对象本身的关键。使用它的常见情况是将对象数组转换为对象的哈希映射。

代码

以下是在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

+0

你应该在问题本身包含任何相关的代码。 – jmar777 2014-10-08 19:34:54

+1

这里有什么问题? – 2017-06-18 00:01:59

回答

-1

以下是小片段我已经在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

+5

请不要推荐扩展'Array.prototype'! – jmar777 2014-10-08 19:34:38

+0

@Naveen I将此代码移动到问题 – hindmost 2014-10-08 19:35:39

+0

啊,我明白了。我最初认为这是一个建议的答案:) – jmar777 2014-10-08 19:37:58

178

这是很容易做到与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 +,所以如果你需要支持旧浏览器,你将需要填充它。

+0

修改了用例以避免混淆。我试图针对JS开发人员在视图驱动应用程序中经常遇到的场景。 – 2014-10-09 09:36:23

+0

正是我在寻找的答案。 – emil 2017-09-13 23:45:05

+2

'result = arr.reduce((map,obj)=>(map [obj.key] = obj。val,map),{});' 对于ES6单线风扇:D – Mtz 2018-01-31 14:44:06

104

使用ES6 Mappretty 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]) 

console.log(result); 
// Map {"foo" => "bar", "hello" => "world"} 
+5

完美!!!!!!!! – Cody 2017-01-30 18:41:37

+3

的作品,但由于某种原因,打字稿的编译器不高兴这个声明 – Blauhirn 2017-11-18 01:51:10

+4

@Blauhirn Typescript和它的类型。尝试使用这一行代替:'var result = arr.map((i):[string,string] => [i.key,i.val])'。因为'Map'接受'条目? [string,string] []''我们必须显式地将传入'map()'的方法的结果作为一对字符串输入。希望这对你有用! – mateuscb 2017-11-20 15:20:00

13

随着lodash,这是可以做到使用keyBy

var arr = [ 
    { key: 'foo', val: 'bar' }, 
    { key: 'hello', val: 'world' } 
]; 

var result = _.keyBy(arr, o => o.key); 

console.log(result); 
// Object {foo: Object, hello: Object} 
0

使用简单的Javascript

var createMapFromList = function(objectList, property) { 
    var objMap = {}; 
    objectList.forEach(function(obj) { 
     objMap[obj[property]] = obj; 
    }); 
    return objMap; 
    }; 
// objectList - the array ; property - property as the key 
+2

在本例中没有使用.map(...)没有意义,因为您不会返回任何内容?在这种情况下,我会建议forEach。 – cuddlecheek 2017-08-27 19:40:43

+0

@cuddlecheek其实是真的..谢谢 – 2017-08-29 03:40:54

0

es2015版本:

const myMap = new Map(objArray.map(obj => [ obj.key, obj.val ])); 
0

采用扩频操作:在jsFiddle代码段

const result = arr.reduce(
    (accumulator, target) => ({ ...accumulator, [target.key]: target.val }), 
    {}); 

示范。