Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

How to convert array to object in JavaScript



Let’s say we need to convert the following array of array into array of objects with keys as English alphabet

const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];

This can be done by mapping over the actual arrays and reducing the subarrays into objects like the below example −

Example

const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
const dataArr = data.map(arr => {
return arr.reduce((acc, cur, index) => ({
   ...acc,
      [String.fromCharCode(97 + index)]: cur
   }), Object.create({}))
});
console.log(dataArr);

Output

The console output for this code will be −

[
   { a: 1, b: 2, c: 3, d: 4 },
   { a: 5, b: 6, c: 7, d: 8 },
   { a: 9, b: 10, c: 11, d: 12 }
]
Updated on: 2020-08-18T07:11:12+05:30

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements