0

Hi I have an array and I want to filter it as I show below. I checked .reduce() , .filter(), .map() functions and couldn't find proper solution. Can you halp me with that? Thanks.

My array:

var pilots = [
  {
    id: 2,
    name: "Wedge Antilles",
    faction: "Rebels",
  },
  {
    id: 8,
    name: "Ciena Ree",
    faction: "Empire",
  },
  {
    id: 40,
    name: "Iden Versio",
    faction: "Empire",
  },
  {
    id: 66,
    name: "Thane Kyrell",
    faction: "Rebels",
  }
];

And I want to filter it like:

var pilots = [
  {
    id: 2
  },
  {
    id: 8
  },
  {
    id: 40
  },
  {
    id: 66
  }
];
  • 1
    Does this answer your question? [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – VLAZ Apr 09 '20 at 10:00
  • 1
    `pilots.map({id} => ({id}))` – VLAZ Apr 09 '20 at 10:01

3 Answers3

0

You can map the array and return only the id

const mapped = pilots.map(({id}) => ({id}));

console.log (mapped)
<script>
var pilots = [
  {
    id: 2,
    name: "Wedge Antilles",
    faction: "Rebels",
  },
  {
    id: 8,
    name: "Ciena Ree",
    faction: "Empire",
  },
  {
    id: 40,
    name: "Iden Versio",
    faction: "Empire",
  },
  {
    id: 66,
    name: "Thane Kyrell",
    faction: "Rebels",
  }
];
</script>
Moritz Roessler
  • 8,542
  • 26
  • 51
0

you can do this way, it will work for you

let pilots = [
    {
      id: 2,
      name: "Wedge Antilles",
      faction: "Rebels",
    },
    {
      id: 8,
      name: "Ciena Ree",
      faction: "Empire",
    },
    {
      id: 40,
      name: "Iden Versio",
      faction: "Empire",
    },
    {
      id: 66,
      name: "Thane Kyrell",
      faction: "Rebels",
    }
  ];


let Items = pilots.map(({ name, faction, ...rest }) => ({ ...rest }));

console.log(Items)

OR

 let result = pilots.map({id} => ({id}))
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24
0

var pilots = [
  {
    id: 2,
    name: "Wedge Antilles",
    faction: "Rebels",
  },
  {
    id: 8,
    name: "Ciena Ree",
    faction: "Empire",
  },
  {
    id: 40,
    name: "Iden Versio",
    faction: "Empire",
  },
  {
    id: 66,
    name: "Thane Kyrell",
    faction: "Rebels",
  }
];

const idOnly = pilots.map(el => ({id :el.id}))

console.log(idOnly)
Sabbin
  • 2,215
  • 1
  • 17
  • 34