How to create an array of objects from multiple arrays in JavaScript ?
Last Updated :
30 Aug, 2024
Creating an array of objects from multiple arrays in JavaScript involves combining corresponding elements from each array into single objects. This approach allows you to efficiently organize related data from separate arrays into a structured format, making it easier to manipulate and access the combined information.
Below are the approaches used to create an array of objects from multiple arrays in JavaScript:
Using a Loop
This approach uses a for loop to iterate through the keys and values arrays, creating an object for each pair and pushing it into an array. The resulting array contains objects with keys from the keys array and corresponding values from the values array.
Example: This example uses a Loop
JavaScript
function createArrayOfObjectsUsingLoop(keys, values) {
let arrayOfObjects = [];
for (let i = 0; i < Math.min(keys.length, values.length); i++) {
let obj = {};
obj[keys[i]] = values[i];
arrayOfObjects.push(obj);
}
return arrayOfObjects;
}
// Example usage:
let keysArray = ['name', 'age', 'city'];
let valuesArray = ['John', 25, 'New York'];
let resultUsingLoop = createArrayOfObjectsUsingLoop(keysArray, valuesArray);
console.log(resultUsingLoop);
Output[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]
Using map Function
The map function is employed to create an array of objects. For each element in the keys array, an object is created with a key-value pair, where the key is from the keys array, and the value is from the corresponding position in the values array.
Example: This example uses map Function
JavaScript
function createArrayOfObjectsUsingMap(keys, values) {
return keys.map(function (key, index) {
let obj = {};
obj[key] = values[index];
return obj;
});
}
// Example usage:
let keysArrayMap = ['name', 'age', 'city'];
let valuesArrayMap = ['John', 25, 'New York'];
let resultUsingMap = createArrayOfObjectsUsingMap(keysArrayMap, valuesArrayMap);
console.log(resultUsingMap);
Output[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]
Using reduce Function
In this approach, the reduce function is used to accumulate objects into an array. For each element in the keys array, an object is created with a key-value pair, and it is pushed into the accumulator array.
Example: This example uses reduce Function
JavaScript
function createArrayOfObjectsUsingReduce(keys, values) {
return keys.reduce(function (acc, key, index) {
let obj = {};
obj[key] = values[index];
acc.push(obj);
return acc;
}, []);
}
// Example usage:
let keysArrayReduce = ['name', 'age', 'city'];
let valuesArrayReduce = ['John', 25, 'New York'];
let resultUsingReduce = createArrayOfObjectsUsingReduce(keysArrayReduce, valuesArrayReduce);
console.log(resultUsingReduce);
Output[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]
Using Object.fromEntries() method along with the map function
This method utilizes Object.fromEntries() along with the map function to create an array of objects. It first zips the keys and values arrays into an array of key-value pairs and then uses Object.fromEntries() to convert each pair into an object.
Example: This example uses Object.fromEntries()
JavaScript
function createArrayOfObjectsUsingFromEntries(keys, values) {
// Ensure both arrays have the same length
const minLength = Math.min(keys.length, values.length);
const keyValuePairs = keys.slice(0, minLength).map((key, index) => [key, values[index]]);
const arrayOfObjects = keyValuePairs.map(pair => Object.fromEntries([pair]));
return arrayOfObjects;
}
// Example usage:
let keysArrayFromEntries = ['name', 'age', 'city'];
let valuesArrayFromEntries = ['John', 25, 'New York'];
let resultUsingFromEntries =
createArrayOfObjectsUsingFromEntries(keysArrayFromEntries, valuesArrayFromEntries);
console.log(resultUsingFromEntries);
Output[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]
Using Array.forEach()
To create an array of objects from multiple arrays in JavaScript using Array.forEach(), iterate over the keys array. For each key, push an object into the result array with the corresponding value from the values array.
Example: In this example we creates an array of objects by pairing elements from two arrays (keys and values). It iterates over keys, using each key to create an object with its corresponding value from values.
JavaScript
const keys = ['name', 'age', 'gender'];
const values = ['Alice', 30, 'female'];
const arrayOfObjects = [];
keys.forEach((key, index) => {
arrayOfObjects.push({ [key]: values[index] });
});
console.log(arrayOfObjects);
Output[ { name: 'Alice' }, { age: 30 }, { gender: 'female' } ]
Using a Custom Zip Function and map
In this method, we’ll first create a custom zip function that combines two arrays into an array of pairs. Then, we’ll use map to convert these pairs into objects.
Custom Zip Function
The custom zip function combines two arrays into an array of arrays where each inner array contains corresponding elements from the input arrays.
Implementation
- Define the
zip Function: This function pairs elements from two arrays into sub-arrays. - Transform Pairs into Objects: Use
map to create an object for each pair.
Example:
JavaScript
function zip(array1, array2) {
const length = Math.min(array1.length, array2.length);
const zipped = [];
for (let i = 0; i < length; i++) {
zipped.push([array1[i], array2[i]]);
}
return zipped;
}
function createArrayOfObjects(keys, values) {
const pairs = zip(keys, values);
return pairs.map(([key, value]) => ({ [key]: value }));
}
const keysArray = ['name', 'age', 'city'];
const valuesArray = ['John', 25, 'New York'];
const result = createArrayOfObjects(keysArray, valuesArray);
console.log(result);
Output[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]