Search code examples
javascriptarraysobject

How to filter and return specific object value from an array of objects


I have an array of objects(data from BE) I need to filter by one specific value and return a list of the IDs of those objects.

This will return the whole object, so i could run in a for loop and append to a new array but seems lengthy.

const data = [{
    id: 1,
    name: "One",
    canAcceptRecruits: true
  },
  {
    id: 2,
    name: "Two",
    canAcceptRecruits: true
  },
  {
    id: 3,
    name: "Three",
    canAcceptRecruits: false
  }, {
    id: 50,
    name: "Fifty",
    canAcceptRecruits: true
  }
];

console.log(data.filter(x => x.canAcceptRecruits == true));

I know i can use a map or a reducer to perform the operation, but i was wondering if there is anything more succinct, nicer perhaps.

Thanks in advance


Solution

  • Array.map seems like the best option.

    const ids = this.props.constants.divisions
      .filter((x) => x.canAcceptRecruits == true)
      .map(x => x.id);