js key array to obj code example
Example 1: javascript Convert an array of objects to a single object
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// Example
toObject(
[
{ id: '1', name: 'June', gender: 'Female' },
{ id: '2', name: 'Alex', gender: 'Male' },
{ id: '3', name: 'Harry', gender: 'Male' },
],
'id'
);
/*
{
'1': { id: '1', name: 'June', gender: 'Female' },
'2': { id: '2', name: 'Alex', gender: 'Male' },
'3': { id: '3', name: 'Harry', gender: 'Male' },
}
*/
Example 2: js array to object with keys
const arr = ['a','b','c'];
const res = arr.reduce((a,b)=> (a[b]='',a),{});
console.log(res)