用例

这个用例是根据提供的字符串或函数将对象数组转换为哈希映射,并将其作为哈希映射中的键来计算和使用,并将值作为对象本身。使用这种方法的常见情况是将对象数组转换为对象的哈希映射。

Code

下面是一个JavaScript小片段,用于将对象数组转换为哈希映射,以object的属性值为索引。您可以提供一个函数来动态计算散列映射的键(运行时)。

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;
};

你可以在这里找到要点:将数组对象转换为HashMap。


当前回答

这就是我在TypeScript中所做的,我有一个小utils库,我在那里放了这样的东西

export const arrayToHash = (array: any[], id: string = 'id') => 
         array.reduce((obj, item) =>  (obj[item[id]] = item , obj), {})

用法:

const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])

或者如果你有一个id以外的标识符

const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')

其他回答

对我来说,我不喜欢使用任何map或reduce,只坚持简单的For循环。

const array = [
   {key: 'a', value: 'b', redundant: 'aaa'},
   {key: 'x', value: 'y', redundant: 'zzz'}
]

const hash = {};

for (const item of array) {
    hash[item.key] = item;
}

console.log(hash);

使用简单的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

这就是我在TypeScript中所做的,我有一个小utils库,我在那里放了这样的东西

export const arrayToHash = (array: any[], id: string = 'id') => 
         array.reduce((obj, item) =>  (obj[item[id]] = item , obj), {})

用法:

const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])

或者如果你有一个id以外的标识符

const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')

您可以使用新的Object.fromEntries()方法。

例子:

Const数组= [ {键:'a',值:'b',冗余:'aaa'}, {key: 'x',值:'y',冗余:'zzz'} ] const hash = Object.fromEntries( 数组中。Map (e => [e;键,e.value]) ) Console.log (hash) // {a: b, x: y}

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