Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
}Advertisements