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' }
console.log(
convertArrayToObject(
[
{ id: 111, name: 'John', age: 29 },
{ id: 112, name: 'Sarah', age: 25 },
{ id: 122, name: 'Kate', age: 22 },
{ id: 123, name: 'Tom', age: 21 },
{ id: 125, name: 'Emma', age: 24 },
],
'id',
),
);
{
111:{ id: 111, name: 'John', age: 29 },
112:{ id: 112, name: 'Sarah', age: 25 },
122:{ id: 122, name: 'Kate', age: 22 },
123:{ id: 123, name: 'Tom', age: 21 },
125:{ id: 125, name: 'Emma', age: 24 }
}