How to use Object.fromEntries() method along with the map function In Javascript
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()
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' } ]
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()