0

For example I have this POST method:

request_salaries(type)

type can be red, blue or green.

The function returns this object:

{
  data: [
    {
     id: 1,
     name: "Linda",
     type: "Red"
    },
    {
      id: 2,
      name: "Mark",
      type: "Green
    },
    {
      id: 3,
      name: "Susan",
      type: "Blue"
    }
  ]
}

Now, I need to return only the sat of data that is passed in the request_salaries(type).

For example, if I request request_salaries(Red)

it should return:

{
  data: [
    {
     id: 1,
     name: "Linda",
     type: "Red"
    },
  ]
}

How can this be achievable?

Thanks.

  • 1
    Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Adrian Aug 08 '18 at 13:43

4 Answers4

3

Just filter out proper values:

const response = { /* your data */ };
const type = 'red';

const filteredResponse = response.data.filter(item => item.type === type)
hsz
  • 148,279
  • 62
  • 259
  • 315
  • 1
    Also don't forget to assign that `filter` array to a new value, `filter` returns an array of items matching the predicate. – James Gould Aug 08 '18 at 13:42
0

Try to filter your returns

request_salaries(type){

// fetch data and set it in array_salaries


return array_salaries.filter(salary => salary.type == type)



}
0

You can use Array.find():

var obj = {
  data: [
    {
     id: 1,
     name: "Linda",
     type: "Red"
    },
    {
      id: 2,
      name: "Mark",
      type: "Green"
    },
    {
      id: 3,
      name: "Susan",
      type: "Blue"
    }
  ]
};
var val = 'Red';
var res = obj.data.find(({type}) => type===val);
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You can use the .find() method

var type = 'red';

const result = response.data.find(function(item) {
    return item.type === type;
});

Using arrow function:

const result = response.data.find( item => item.type === type );
Chibuzo
  • 6,112
  • 3
  • 29
  • 51