0

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?

Smeagol
  • 61
  • 6
  • Use [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)? Though if you don't need this data client-side, it would make a lot more sense to filter it server-side. – David Jul 24 '22 at 14:48
  • Answered here https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-of-property – Sean Jul 24 '22 at 14:54
  • I edited the question, it's an array of objects, and every object has a property, isActive, that's the property I need to filter the array of objects on, so I need an entire array of objects that are active, and all not active filtered out – Smeagol Jul 24 '22 at 15:05

3 Answers3

1

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);
  }
  • How do I filter on all objects in the array? I can access the first object like so: console.log(response.data.data[0]); I need to filter all the objects that have response.data.data.isActive === true. I tried const resultFiltered = response.filter(obj => Boolean(obj.data.data.isAddon) === true); but I get Uncaught (in promise) TypeError: response.filter is not a function – Smeagol Jul 24 '22 at 16:21
  • try response.data.data.filter(obj => Boolean(obj.isActive) === true) – Suman Anandan Jul 24 '22 at 16:27
0

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);

saggy2001
  • 26
  • 3
0

Test the bellow code:

response.data.filter()

QasemBSK
  • 190
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 26 '22 at 00:00