Home > OS >  Filter Array of objects (API response) based on flag in database
Filter Array of objects (API response) based on flag in database

Time:07-25

I am receiving a large array of objects using the below method:

const GetList = async () => {
  const [data, error] = await GetList();
  console.log(response);

This gives me back an array of 1000 elements, there is an isActive flag on every element and I need to filter out the elements that are not active.

I am not able to use

var resultFiltered = response.filter(obj =>{
  return obj.isActive === 'true'
});

As it gives me an error message enter image description here

The entire array is stored in the data variable, how can I filter out all elements that are not active?

CodePudding user response:

I'm not sure why you are using response variable, since the value is fetched variable data, try filtering as shown below

  const GetList = async () => {
    const data = await GetList();
    const resultFiltered = data.filter(obj => Boolean(obj.isActive) === true);
    console.log(resultFiltered);
  }

CodePudding user response:

According to the error, the response variable is not an array-type variable please check that out. If it's an object then convert it into an array and then apply the filter function.

const resultFiltered = Object.values(response).filter(obj => obj.isActive === true);

CodePudding user response:

Test the bellow code:

response.data.filter()

  • Related