0

I'm trying to extract specific value from JSON object using the following code:

 data: any[] = [
    {'id': 1, 'expenseType': {'id': 1, 'name': 'type1'} , 'cost': 100},
    {'id': 2, 'expenseType': {'id': 2, 'name': 'type2'}, 'cost': 200 },
    {'id': 3, 'expenseType': {'id': 3, 'name': 'type3'}, 'cost': 300} }
];

 filterData = this.data.map(({ expenseType }) => ({
   expenseType   
 }));

I want the filterData to be an array of:

[{'id': 1, 'name': 'type1'},{'id': 2, 'name': 'type2'}, {'id': 3, 'name': 'type3']

The problem is that the key is also included.

Can I achieve this using array.map()?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bad_Pan
  • 488
  • 13
  • 20
  • `({ expenseType }) => expenseType`…? – deceze Feb 10 '20 at 08:41
  • If you don't want another object, why do you build one? Either copy (`=> ({ ...expenseType })`, see *"destructuring"*) or just return (`=> expenseType`) the object you want. – jonrsharpe Feb 10 '20 at 08:41

1 Answers1

5

You need just to return expenseType, without using it as short hand property.

var data = [{ id: 1, expenseType: { id: 1, name: 'type1' }, cost: 100  }, { id: 2, expenseType: { id: 2, name: 'type2' }, cost: 200 }, { id: 3, expenseType: { id: 3,  name: 'type3' }, cost: 300 }],
    filterData = data.map(({ expenseType }) => expenseType);

console.log(filterData);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392