How to use Array.forEach() In Javascript
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.
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' } ]
How to create an array of objects from multiple arrays in JavaScript ?
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:
Table of Content
- Using a Loop
- Using map Function
- Using reduce Function
- Using Object.fromEntries() method along with the map function
- Using Array.forEach()