The use case is to convert an array of objects into a hash map based on string or function provided to evaluate and use as the key in the hash map and val
You can use the new Object.fromEntries() method.
Example:
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}
This is fairly trivial to do with 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' }
Note: Array.prototype.reduce()
is IE9+, so if you need to support older browsers you will need to polyfill it.
Using the spread operator:
const result = arr.reduce(
(accumulator, target) => ({ ...accumulator, [target.key]: target.val }),
{});
Demonstration of the code snippet on jsFiddle.
Using simple 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
try
let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});
let arr=[
{id:123, name:'naveen'},
{id:345, name:"kumar"}
];
let fkey = o => o.id; // function changing object to string (key)
let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});
console.log( toHashMap(arr,fkey) );
// Adding to prototype is NOT recommented:
//
// Array.prototype.toHashMap = function(f) { return toHashMap(this,f) };
// console.log( arr.toHashMap(fkey) );
With lodash
:
const items = [
{ key: 'foo', value: 'bar' },
{ key: 'hello', value: 'world' }
];
const map = _.fromPairs(items.map(item => [item.key, item.value]));
console.log(map); // { foo: 'bar', hello: 'world' }
Link to lodash