convert array of objects to object of objects javascript 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 }), {});
toObject(
[
{ id: '1', name: 'June', gender: 'Female' },
{ id: '2', name: 'Alex', gender: 'Male' },
{ id: '3', name: 'Harry', gender: 'Male' },
],
'id'
);
Example 2: convert array to object javascript
const convertArrayToObject = (array, key) =>
array.reduce(
(obj, item) => ({
...obj,
[item[key]]: item
}),
{}
);
Example 3: javascript convert array to object
function arrayToObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
obj[i] = arr[i];
}
return obj;
}
var colors=["red","blue","green"];
var colorsObj=arrayToObject(colors);