How to convert array into array of objects using map() and reduce() in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of arrays like this −

const arr = [
   [
      ['juice', 'apple'], ['maker', 'motts'], ['price', 12]
   ],
   [
      ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]
   ]
];

We are required to write a JavaScript function that takes in one such array and returns a new array of objects built based on the input array.

So, for the above array, the output should look like this −

const output = [
   {juice: 'apple', maker: 'motts', price: 12},
   {juice: 'orange', maker: 'sunkist', price: 11}
];

Example

The code for this will be −

const arr = [
   [
      ['juice', 'apple'], ['maker', 'motts'], ['price', 12]
   ],
   [
      ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]
   ]
];
const arrayToObject = arr => {
   let res = [];
   res = arr.map(list => {
      return list.reduce((acc, val) => {
         acc[val[0]] = val[1];
         return acc;
      }, {});
   });
   return res;
};
console.log(arrayToObject(arr));

Output

The output in the console −

[
   { juice: 'apple', maker: 'motts', price: 12 },
   { juice: 'orange', maker: 'sunkist', price: 11 }
][
   { juice: 'apple', maker: 'motts', price: 12 },
   { juice: 'orange', maker: 'sunkist', price: 11 }
]
raja
Published on 10-Oct-2020 11:23:42
Advertisements