How to extract value of a property as array from an array of objects in JavaScript?

Here’s how to extract values of a specific property from an array of objects in JavaScript, along with multiple methods and examples:

1. Using Array.map() (Most Common)

Extract values from a property and return them as an array:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

// Extract all 'name' values
const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']

2. Handling Missing Properties

Safely extract values when some objects might lack the property:

const products = [
  { id: 1, price: 10 },
  { id: 2 }, // No price
  { id: 3, price: 20 }
];

// Extract prices and filter undefined values
const prices = products
  .map(product => product.price)
  .filter(price => price !== undefined);

console.log(prices); // [10, 20]

3. Using for Loop (Legacy Approach)

For environments without ES6 support:

const names = [];
for (let i = 0; i < users.length; i++) {
  names.push(users[i].name);
}

4. Extract Nested Properties

Access properties in nested objects:

const orders = [
  { id: 1, customer: { name: 'Alice' } },
  { id: 2, customer: { name: 'Bob' } }
];

const customerNames = orders.map(order => order.customer.name);
console.log(customerNames); // ['Alice', 'Bob']

5. Using Array.from()

Alternative approach with array initialization:

const names = Array.from(users, user => user.name);

6. Get Unique Values Only

Extract distinct values using Set:

const duplicates = [2, 2, 3, 4, 4];
const uniqueValues = [...new Set(duplicates)];
console.log(uniqueValues); // [2, 3, 4]

Complete Example with Edge Cases

const data = [
  { id: 1, value: 'A' },
  { id: 2 }, // Missing 'value'
  null, // Invalid object
  { id: 3, value: 'B' }
];

// Safe extraction with error handling
const values = data
  .filter(item => item?.value) // Remove null/undefined and items without 'value'
  .map(item => item.value);

console.log(values); // ['A', 'B']

Key Notes

  • Method
  • Small datasets: All methods work equally well
  • Large datasets: for loops are marginally faster (but less readable)
  • Modern engines: Optimized map performance

Leave a Reply

Your email address will not be published. Required fields are marked *