Converting array of arrays into an object in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of arrays that contains the performance of a cricket player like this −

const arr = [
   ['Name', 'V Kohli'],
   ['Matches', 13],
   ['Runs', 590],
   ['Highest', 183],
   ['NO', 3],
   ['SR', 131.5]
];

We are required to write a JavaScript function that takes in one such array of arrays. Here, each subarray represents one key-value pair, the first element being the key and the second its value. The function should construct an object based on the key-value pairs in the array and return the object.

Therefore, for the above array, the output should look like −

const output = {
   Name: 'V Kohli',
   Matches: 13,
   Runs: 590,
   Highest: 183,
   NO: 3,
   SR: 131.5
};

Example

Following is the code −

const arr = [
   ['Name', 'V Kohli'],
   ['Matches', 13],
   ['Runs', 590],
   ['Highest', 183],
   ['NO', 3],
   ['SR', 131.5]
];
const arrayToObject = (arr = []) => {
   const res = {};
   for(pair of arr){
      const [key, value] = pair;
      res[key] = value;
   };
   return res;
};
console.log(arrayToObject(arr));

Output

Following is the output on console −

{
   Name: 'V Kohli',
   Matches: 13,
   Runs: 590,
   Highest: 183,
   NO: 3,
   SR: 131.5
}
raja
Published on 10-Dec-2020 08:25:28
Advertisements