React by Patrik

Returning Only Specific Fields from Filtered Data in JavaScript

Overview: In some cases, you may want to return only specific fields from filtered data, such as extracting only the name from a list of people. This Snipp demonstrates how to combine filtering and mapping to achieve this.

Implementation:

// Filter by gender and return only names
const maleNames = namesWithAttributes
  .filter(person => person.gender === "male")
  .map(person => person.name);
console.log(maleNames);
// Output: ["Norbert", "Henrik", "Claus"]

This approach combines the filter() and map() methods to first filter the data by gender and then extract only the name field from the resulting objects.

JavaScript
Field

Comments