Sometimes, we want to return an array of objects with the JavaScript array map method.
In this article, we’ll look at how to return an array of objects with the JavaScript array map method.
How to return an array of objects with the JavaScript array map method?
To return an array of objects with the JavaScript array map method, we can return an object in the map callback.
For instance, we write
const rockets = [
{ country: "US", launches: 23 },
{ country: "China", launches: 16 },
{ country: "Europe", launches: 7 },
{ country: "India", launches: 4 },
{ country: "Japan", launches: 3 },
];
const launchOptimistic = rockets.map((elem) => {
const { country, launches } = elem;
return {
country,
launches: launches + 10,
};
});
console.log(launchOptimistic);
to call rockets.map with a callback that returns an object with the new launches value and the same country value.
Conclusion
To return an array of objects with the JavaScript array map method, we can return an object in the map callback.