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 combine 2 arrays into 1 object in JavaScript
Let's say, we have two arrays of equal lengths and are required to write a function that maps the two arrays into an object. The corresponding elements of the first array becomes the corresponding keys of the object and the elements of the second array become the value.
We will reduce the first array, at the same time accessing elements of the second array by index. This is a common pattern for creating objects from parallel arrays.
Using Array.reduce() Method
const keys = [
'firstName',
'lastName',
'isEmployed',
'occupation',
'address',
'salary',
'expenditure'
];
const values = [
'Hitesh',
'Kumar',
false,
'Frontend Developer',
'Tilak Nagar, New Delhi',
90000,
45000
];
const combineArrays = (first, second) => {
return first.reduce((acc, val, ind) => {
acc[val] = second[ind];
return acc;
}, {});
};
console.log(combineArrays(keys, values));
{
firstName: 'Hitesh',
lastName: 'Kumar',
isEmployed: false,
occupation: 'Frontend Developer',
address: 'Tilak Nagar, New Delhi',
salary: 90000,
expenditure: 45000
}
Using Object.fromEntries() Method
A more modern approach uses Object.fromEntries() with map() to create key-value pairs:
const keys = ['name', 'age', 'city'];
const values = ['Alice', 30, 'New York'];
const combineWithEntries = (keys, values) => {
return Object.fromEntries(
keys.map((key, index) => [key, values[index]])
);
};
console.log(combineWithEntries(keys, values));
{
name: 'Alice',
age: 30,
city: 'New York'
}
Using for...of Loop
A simple loop approach for better readability:
const keys = ['product', 'price', 'inStock'];
const values = ['Laptop', 999, true];
const combineWithLoop = (keys, values) => {
const result = {};
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
return result;
};
console.log(combineWithLoop(keys, values));
{
product: 'Laptop',
price: 999,
inStock: true
}
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| Array.reduce() | Good | Good | Excellent |
| Object.fromEntries() | Excellent | Good | ES2019+ |
| for...of Loop | Excellent | Best | Excellent |
Conclusion
Use Object.fromEntries() for modern codebases and Array.reduce() for broader compatibility. Both methods efficiently combine parallel arrays into objects.
