array to objects code example
Example 1: js array into object
const names = ['Alex', 'Bob', 'Johny', 'Atta'];
const obj = Object.assign({}, names);
console.log(obj);
Example 2: javascript object to array
fooArray = Object.entries(fooObj);
fooArray.forEach(([key, value]) => {
console.log(key);
console.log(value);
})
Example 3: convert array to object javascript
const convertArrayToObject = (array, key) =>
array.reduce(
(obj, item) => ({
...obj,
[item[key]]: item
}),
{}
);
Example 4: 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 5: 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);