Syntax error Converting array of arrays into an object in JavaScript

Converting array of arrays into an object in JavaScript



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
}
Updated on: 2020-12-10T08:25:39+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements