Common Map Patterns
You'll learn how to use map() for everyday tasks like extracting object properties, converting data types, and building new objects from array elements.
The Most Useful Map Recipes
While map() can transform data in countless ways, a few patterns appear constantly in real-world code. Mastering these will make you productive immediately.
Extracting a Single Property
When you have an array of objects but only need one property from each:
const users = [
{ name: 'Alice', age: 28 },
{ name: 'Bob', age: 34 },
{ name: 'Carol', age: 22 }
];
const names = users.map(user => user.name);
// ['Alice', 'Bob', 'Carol']
Think of this like scanning a table and copying just one column.
Converting Data Types
Transform each element into a different type:
const numbers = ['5', '12', '8', '23'];
const parsed = numbers.map(str => Number(str));
// [5, 12, 8, 23]
const doubled = [1, 2, 3].map(n => String(n * 2));
// ['2', '4', '6']
Building New Objects
Create objects from simpler values:
const ids = [101, 102, 103];
const records = ids.map(id => {
return { id: id, status: 'active' };
});
// [{ id: 101, status: 'active' }, { id: 102, status: 'active' }, ...]
Or transform existing objects into new shapes:
const products = [
{ name: 'Laptop', price: 999 },
{ name: 'Mouse', price: 25 }
];
const formatted = products.map(p => {
return { item: p.name, cost: `$${p.price}` };
});
// [{ item: 'Laptop', cost: '$999' }, { item: 'Mouse', cost: '$25' }]
Key Takeaway: The most common map() patterns are extracting properties from objects, converting between data types, and reshaping objects — once you recognize these patterns, most data transformations become straightforward.