Question

Extract Object Property Values with JavaScript Array.map()

javascriptjavascript-objects

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 foo or bar.
  • 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.

Take Quiz

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:

function getFields(items, field) {
  return items.map((item) => item[field]);
}

console.log(getFields(objArray, "foo")); // [1, 3, 5]
console.log(getFields(objArray, "bar")); // [2, 4, 6]

item[field] means “look up the property whose name is contained in field.” By contrast, item.field would always look for a property literally named field.

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:

  1. items.map(...) starts with an empty result array internally.
  2. The first object is { name: "Ada", score: 10 }.
    • The callback returns item.score, which is 10.
    • The result array becomes [10].
  3. The second object has a score of 15.
    • The result array becomes [10, 15].
  4. The third object has a score of 12.
    • The result array becomes [10, 15, 12].
  5. map() returns that new array and assigns it to scores.
console.log(scores); // [10, 15, 12]
console.log(items);  // original objects are still present

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.
    const orderNumbers = orders.map(order => order.orderNumber);
    
Take Quiz

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.name.trim());

Build UI-friendly objects

Rather than extracting one primitive value, projects often map API data into a shape required by a component:

const options = categories.map((category) => ({
  value: category.id,
  label: category.name
}));

Use map() when every input item should create one output item. If you need to discard items, combine it with filter() or use flatMap() when appropriate.

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:

const values = objArray.map((item) => {
  return item.foo;
});

Or use the concise form:

const values = objArray.map(item => item.foo);

Expecting map() to remove missing values

map() preserves the input length. A missing property becomes undefined:

const items = [{ foo: 1 }, {}, { foo: 3 }];

console.log(items.map(item => item.foo)); // [1, undefined, 3]

Filter first if missing values should be omitted.

Using forEach() when you need a returned array

forEach() is intended for side effects and returns undefined:

const values = objArray.forEach(item => item.foo);

console.log(values); // undefined

Use map() to create a transformed array.

Comparisons

ToolMain purposeReturn valueBest use here?
map()Transform every array itemA new arrayYes; extract one value per object
forEach()Perform a side effect for each itemundefinedNo, unless manually pushing into another array
filter()Keep only items that pass a testA new, possibly shorter arrayUse before map() to remove unwanted objects
reduce()Combine items into one accumulated resultAny accumulated valuePossible, but less direct for simple extraction
for loopManual iteration and controlWhatever you buildValid when you need complex control flow

For simple property extraction, this is the most readable choice:

const fooValues = objArray.map(item => item.foo);

Use bracket notation for a variable key:

const values = objArray.map(item => item[field]);
Take Quiz

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.foo is for a known property name.
  • item[field] is for a property name stored in a variable.
  • Missing properties produce undefined.
  • map() does not mutate the original array unless the callback itself mutates objects.

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]

Can I extract nested properties with map()?

Yes, when every level exists:

const cities = users.map(user => user.address.city);

If a nested object may be missing, use optional chaining:

const cities = users.map(user => user.address?.city);

Why not use forEach() for this?

You can, but you must create an output array and push values manually. map() directly communicates that you are transforming an array into another array.

Can map() extract more than one property?

Yes. Return a new object or array from the callback:

const summaries = users.map(user => ({ id: user.id, name: user.name }));
Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more