JavaScript - Create Array of Objects From Multiple Arrays
Last Updated :
24 Jan, 2025
Here are the different methods to create an array of objects from multiple arrays in JavaScript:
1. Using map (Most Popular Approach)
The map method is widely used because it is simple, concise, and works efficiently for arrays of the same length.
JavaScript
const a = ["apple", "banana", "orange"];
const n = [10, 20, 30];
const res = a.map((item, index) => {
return { item, count: n[index] };
});
console.log(res);
Output[
{ item: 'apple', count: 10 },
{ item: 'banana', count: 20 },
{ item: 'orange', count: 30 }
]
In this example
- The map method iterates over the array.
- For each element, it creates an object with items from the array.
- The index ensures elements from both arrays are matched correctly.
2. Using for Loop (Flexible Approach)
A traditional for loop gives more control and works well for arrays of varying lengths.
JavaScript
const a = ["car", "bike", "bus"];
const n = [5, 15, 25];
const res = [];
for (let i = 0; i < a.length; i++) {
res.push({ vehicle: a[i], count: n[i] });
}
console.log(res);
Output[
{ vehicle: 'car', count: 5 },
{ vehicle: 'bike', count: 15 },
{ vehicle: 'bus', count: 25 }
]
- The loop runs for the length of the array.
- At each iteration, it creates an object and pushes it into the result array.
- The n[i] ensures values are picked from the second array.
3. Using reduce (Advanced Approach)
The reduce method can be used to build an array of objects while accumulating results.
JavaScript
const a = ["pen", "pencil", "eraser"];
const n = [2, 5, 3];
const res = a.reduce((acc, item, index) => {
acc.push({ product: item, quantity: n[index] });
return acc;
}, []);
console.log(res);
Output[
{ product: 'pen', quantity: 2 },
{ product: 'pencil', quantity: 5 },
{ product: 'eraser', quantity: 3 }
]
- reduce initializes an empty array as the accumulator (acc).
- For each element in a, an object is created using item and n[index].
- The object is pushed into the accumulator, which is returned at the end.
4. Handling Arrays of Different Lengths
When the arrays have different lengths, you can stop the iteration at the shortest array.
JavaScript
const a = ["rose", "lily"];
const n = [100, 200, 300];
const res = [];
const minLength = Math.min(a.length, n.length);
for (let i = 0; i < minLength; i++) {
res.push({ flower: a[i], price: n[i] });
}
console.log(res);
Output[ { flower: 'rose', price: 100 }, { flower: 'lily', price: 200 } ]
- The Math.min function ensures the loop runs only up to the shortest array length.
- This prevents errors caused by accessing out-of-bound indices.
5. Custom Zip Function for Reusability
If you frequently combine arrays, you can create a reusable zip function.
JavaScript
const zip = (keys, values) => {
return keys.map((key, index) => {
return { [key]: values[index] };
});
};
const a = ["item1", "item2", "item3"];
const n = [1, 2, 3];
const res = zip(a, n);
console.log(res);
Output[ { item1: 1 }, { item2: 2 }, { item3: 3 } ]
- The zip function combines the keys and values into an array of objects.
- It works generically for any two arrays.
Conclusion
- For simplicity and readability, map is the most popular and widely used method.
- Use for loops for more control and flexibility.
- Use reduce for advanced use cases.
- Always handle edge cases, such as arrays of different lengths, to avoid errors.
- For reusable solutions, create custom helper functions like zip.
Similar Reads
JavaScript - Create an Object From Two Arrays Here are the different methods to create an object from two arrays in JavaScript1. Using for-each loopThe arr.forEach() method calls the provided function once for each element of the array. JavaScriptconst a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi']; const res = {}; a1.forEac
3 min read
JavaScript - Create Partial Objects Array from Another Array Here are the different ways to create an array of partial objects from another array in JavaScript1. Using map()The map() method is the most efficient and commonly used way to extract specific properties from objects in an array. It creates a new array by transforming each object.JavaScriptconst a =
4 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ? Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional struct
3 min read
How to convert a map to array of objects in JavaScript? A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
Different Ways to Crate an Array of Objects in JavaScript ? Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you
3 min read
How to Create an Array of Object Literals in a Loop using JavaScript? Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript. Here are different app
5 min read