How to convert object of arrays collections into array of object
From
const obj = {
name: ['Sam', 'John', 'Paul'],
age: [25, 35, 22],
profession: ['Developer', 'Tester', 'Manager']
}
To
const collections = [
{name: 'Sam', age: 25, profession: 'Developer'},
{name: 'John', age: 35, profession: 'Tester'},
{name: 'Paul', age: 22, profession: 'Manager'}
]
2
Answers
Here are two ways to convert an object of arrays into an array of objects in JavaScript:
Method 1: Using map and Object.values:
JavaScript
Use code with caution. Learn more
Explanation:
Object.values(obj[0]) extracts the values of the first array in the object (the names).
The map method iterates over these values and creates a new object for each one, using the corresponding values from the other arrays.
Method 2: Using nested forEach loops:
JavaScript
Use code with caution. Learn more
Explanation:
The outer forEach loop iterates over the keys of the object.
The inner forEach loop iterates over the values of each array.
It creates a new object in the collections array if it doesn’t exist yet, and assigns the value to the corresponding key.
Key points:
Assumed Array Length: Both methods assume that all arrays within the object have the same length.
Conciseness: The first method using map and Object.values is generally more concise and readable.
Readability: The second method using nested forEach loops might be more intuitive for those less familiar with map.
Choose the method that you find more comfortable and understandable!
Here is an example of a simple way to get an array of objects from object of arrays as above by using reduce: