Question
Given this JavaScript array of objects:
const objArray = [
{ foo: 1, bar: 2 },
{ foo: 3, bar: 4 },
{ foo: 5, bar: 6 }
];
How can you extract the value of one property from every object into a new array? For example, extracting the foo property should produce:
[1, 3, 5]
A loop can do this:
function getFields(input, field) {
const output = [];
for (let i = 0; i < input.length; i += 1) {
output.push(input[i][field]);
}
return output;
}
const result = getFields(objArray, "foo");
Is there a more idiomatic JavaScript approach that does not require a custom utility function?
Short Answer
You will learn how to transform an array of objects into an array of property values with Array.prototype.map(). You will also learn when to use dot notation versus bracket notation, what happens when properties are missing, and how this pattern appears in real applications.
Concept
Array.prototype.map() creates a new array by running a callback once for every item in an existing array.
When each item is an object, the callback can return one property from that object. This makes map() a natural tool for extracting a column-like set of values from object records.
const values = objArray.map((item) => item.foo);
console.log(values); // [1, 3, 5]
The original objArray is not changed. map() returns a separate array containing exactly one result for each original item.
This matters because arrays of objects are common in JavaScript: API responses, database records, form data, product lists, and user lists often have this shape. map() expresses the intent clearly: “transform every item.”
Mental Model
Think of an array of objects as a stack of forms:
- Each form is one object.
- Each labeled field on the form is a property such as
fooorbar. map()reads the same field from every form and writes those values onto a new list.
For example, reading the foo field from three forms produces a list of the three foo values. The forms remain unchanged; you only create a new list of selected values.
Syntax and Examples
The basic syntax is:
const result = array.map((item) => item.propertyName);
For the example array:
const objArray = [
{ foo: 1, bar: 2 },
{ foo: 3, bar: 4 },
{ foo: 5, bar: 6 }
];
const fooValues = objArray.map((item) => item.foo);
console.log(fooValues); // [1, 3, 5]
The shorter callback form is also common:
const fooValues = objArray.map(item => item.foo);
Selecting a dynamic property
Use bracket notation when the property name is stored in a variable or passed as an argument:
Step by Step Execution
Consider this code:
const items = [
{ name: "Ada", score: 10 },
{ name: "Lin", score: 15 },
{ name: "Sam", score: 12 }
];
const scores = items.map((item) => item.score);
Execution proceeds as follows:
items.map(...)starts with an empty result array internally.- The first object is
{ name: "Ada", score: 10 }.- The callback returns
item.score, which is10. - The result array becomes
[10].
- The callback returns
- The second object has a score of
15.- The result array becomes
[10, 15].
- The result array becomes
- The third object has a score of
12.- The result array becomes .
Real World Use Cases
Property extraction with map() is useful whenever you need a simpler list from structured records.
- API responses: Get user IDs before making another request.
const userIds = users.map(user => user.id); - Dropdown options: Extract category names for a menu.
const labels = categories.map(category => category.name); - Charts: Extract numeric values to plot.
const dailySales = reports.map(report => report.sales); - Form validation: Collect email addresses entered in repeated form rows.
const emails = contacts.map(contact => contact.email); - Logging and reporting: Build a list of order numbers.
orderNumbers = orders.( order.);
Real Codebase Usage
In production code, map() is often part of a small data-processing pipeline.
Filter invalid records, then extract values
If some objects may not contain the desired property, filter first when undefined should not appear in the result:
const products = [
{ name: "Keyboard", price: 80 },
{ name: "Sticker" },
{ name: "Mouse", price: 45 }
];
const prices = products
.filter((product) => product.price !== undefined)
.map((product) => product.price);
console.log(prices); // [80, 45]
Transform values while extracting
The callback can return a modified value rather than the property unchanged:
const names = users.map((user) => user..());
Common Mistakes
Using dot notation with a variable property name
This does not select the property named by the value of field:
const field = "foo";
const value = objArray[0].field;
console.log(value); // undefined
It searches for a property literally called field. Use brackets for a dynamic key:
const value = objArray[0][field];
console.log(value); // 1
Forgetting to return from a block callback
Arrow functions with braces need an explicit return:
const values = objArray.map((item) => {
item.foo;
});
console.log(values); // [undefined, undefined, undefined]
Correct version:
Comparisons
| Tool | Main purpose | Return value | Best use here? |
|---|---|---|---|
map() | Transform every array item | A new array | Yes; extract one value per object |
forEach() | Perform a side effect for each item | undefined | No, unless manually pushing into another array |
filter() | Keep only items that pass a test | A new, possibly shorter array | Use before map() to remove unwanted objects |
reduce() | Combine items into one accumulated result | Any accumulated value | Possible, but less direct for simple extraction |
Cheat Sheet
// Extract a known property
const names = users.map(user => user.name);
// Extract a property selected at runtime
const field = "email";
const values = users.map(user => user[field]);
// Convert while extracting
const idsAsText = users.map(user => String(user.id));
// Exclude missing values first
const emails = users
.filter(user => user.email !== undefined)
.map(user => user.email);
map()creates a new array.- The output has the same number of items as the input.
item.foois for a known property name.item[field]is for a property name stored in a variable.- Missing properties produce
undefined.
FAQ
How do I get a property from every object in a JavaScript array?
Use map():
const ids = users.map(user => user.id);
Does map() modify the original array?
No. map() returns a new array. However, if you modify object properties inside the callback, you can still mutate the original objects because objects are referenced values.
Should I use item.foo or item["foo"]?
Both work for a fixed property name. Dot notation, item.foo, is usually clearer. Use brackets when the property name comes from a variable, such as item[field].
What happens if an object does not have the requested property?
The extracted value is undefined for that object.
[{ foo: 1 }, {}].map(item => item.foo); // [1, undefined]
Mini Project
Description
Create a small report helper for an order list. The helper will extract selected fields from order objects and calculate a total for valid order amounts. This reflects a common task when preparing API data for a report or interface.
Goal
Extract order IDs and valid amounts from an array of order objects using map() and filter().
Requirements
Return an array containing every order ID.
Return an array containing only defined order amounts.
Calculate the total of the defined amounts.
Use map() to extract values.
Do not mutate the original order array.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.