
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
Store Two Arrays as Key-Value Pair in One Object in JavaScript
Suppose, we have two arrays of literals of same length like these −
const arr1 = ['firstName', 'lastName', 'age', 'address', 'isEmployed']; const arr2 = ['Rahul', 'Sharma', 23, 'Tilak Nagar', false];
We are required to write a JavaScript function that takes in two such arrays.
The function should construct an object mapping the elements of the second array to the corresponding elements of the first array.
We will use the Array.prototype.reduce() method to iterate over the arrays, building the object.
Example
The code for this will be −
const arr1 = ['firstName', 'lastName', 'age', 'address', 'isEmployed']; const arr2 = ['Rahul', 'Sharma', 23, 'Tilak Nagar', false]; const mapArrays = (arr1 = [], arr2 = []) => { const res = arr1.reduce((acc,elem,index) =>{ acc[elem]=arr2[index]; return acc; },{}); return res; }; console.log(mapArrays(arr1, arr2));
Output
And the output in the console will be −
{ firstName: 'Rahul', lastName: 'Sharma', age: 23, address: 'Tilak Nagar', isEmployed: false }
Advertisements