Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to store two arrays as a keyvalue 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.
Method 1: Using Array.reduce()
We will use the Array.prototype.reduce() method to iterate over the arrays, building the object.
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));
{
firstName: 'Rahul',
lastName: 'Sharma',
age: 23,
address: 'Tilak Nagar',
isEmployed: false
}
Method 2: Using Object.fromEntries() with Array.map()
A more concise approach using modern JavaScript methods:
const arr1 = ['firstName', 'lastName', 'age', 'address', 'isEmployed'];
const arr2 = ['Rahul', 'Sharma', 23, 'Tilak Nagar', false];
const mapArraysModern = (keys, values) => {
return Object.fromEntries(keys.map((key, index) => [key, values[index]]));
};
console.log(mapArraysModern(arr1, arr2));
{
firstName: 'Rahul',
lastName: 'Sharma',
age: 23,
address: 'Tilak Nagar',
isEmployed: false
}
Method 3: Using a Simple for Loop
For better performance with large arrays, use a traditional loop:
const arr1 = ['firstName', 'lastName', 'age', 'address', 'isEmployed'];
const arr2 = ['Rahul', 'Sharma', 23, 'Tilak Nagar', false];
const mapArraysLoop = (keys, values) => {
const result = {};
for (let i = 0; i
{
firstName: 'Rahul',
lastName: 'Sharma',
age: 23,
address: 'Tilak Nagar',
isEmployed: false
}
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| Array.reduce() | Good | Good | All modern browsers |
| Object.fromEntries() | Excellent | Good | ES2019+ |
| For loop | Fair | Best | All browsers |
Conclusion
Use Object.fromEntries() for modern, readable code. For maximum compatibility or performance with large datasets, use the for loop approach. Array.reduce() offers a good balance between readability and compatibility.
