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
Selected Reading
How to combine two arrays into an array of objects in JavaScript?
Combining two arrays into an array of objects is a common task in JavaScript. This allows you to pair corresponding elements from both arrays into structured data.
Using map() with Object Creation
The map() method creates a new array by transforming each element. We can use it to combine arrays into objects:
var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike', 'Sam', 'Carol'];
var arrayOfObjects = firstArray.map(function(value, index) {
return {
first: value,
second: secondArray[index]
};
});
console.log("Original Arrays:");
console.log("First:", firstArray);
console.log("Second:", secondArray);
console.log("\nCombined Objects:");
console.log(arrayOfObjects);
Original Arrays:
First: [ 'John', 'David', 'Bob' ]
Second: [ 'Mike', 'Sam', 'Carol' ]
Combined Objects:
[
{ first: 'John', second: 'Mike' },
{ first: 'David', second: 'Sam' },
{ first: 'Bob', second: 'Carol' }
]
Using ES6 Arrow Functions
Modern JavaScript allows for more concise syntax using arrow functions:
const names = ['Alice', 'Bob', 'Charlie'];
const ages = [25, 30, 35];
const people = names.map((name, index) => ({
name: name,
age: ages[index]
}));
console.log(people);
[
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
]
Creating Array of Arrays
If you prefer arrays instead of objects, you can create nested arrays:
var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike', 'Sam', 'Carol'];
var arrayPairs = firstArray.map(function(value, index) {
return [value, secondArray[index]];
});
console.log(arrayPairs);
[ [ 'John', 'Mike' ], [ 'David', 'Sam' ], [ 'Bob', 'Carol' ] ]
Handling Unequal Array Lengths
When arrays have different lengths, the longer array's extra elements are ignored:
const colors = ['red', 'blue', 'green', 'yellow'];
const numbers = [1, 2, 3];
const combined = colors.map((color, index) => ({
color: color,
number: numbers[index] || null
}));
console.log(combined);
[
{ color: 'red', number: 1 },
{ color: 'blue', number: 2 },
{ color: 'green', number: 3 },
{ color: 'yellow', number: null }
]
Conclusion
Use map() to combine arrays into objects by pairing elements at corresponding indices. This technique is useful for creating structured data from separate arrays.
Advertisements
