convert array of objects to object js code example
Example 1: how to convert an array into an object using javascript
const arrToInstanceCountObj = arr => arr.reduce((obj, e) => {
obj[e] = (obj[e] || 0) + 1;
return obj;
}, {});
arrToInstanceCountObj(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'])
Example 2: 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);