how to convert single array into object in javascript 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 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 3: 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'])