2014-10-08 82 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 }), 
    {}); 

示範。