How to use map Function In Javascript
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
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' } ]
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()