Home > front end >  Can't filter object returns empty array
Can't filter object returns empty array

Time:02-27

I'm a student learning ReactNative. Im tying to filter some objects based on another object. So Im getting data from an API. These are for example receipts:

[
  {
    "id": 1,
    "name": "test",
    "category": {
        "id": 1,
        "name": "Cookies",
    },
  },
  {
    "id": 2,
    "name": "test2",
    "category": {
        "id": 2,
        "name": "Candy",
    },
  }
]

Then Im trying to filter the objects on category. So for example I only want to show the items which are from category Candy. Ive created a function for this:

    function onSelectCategory(category) {
        let receiptsList = receipts.filter((a) =>
            a.category.includes(category.name)
        );

        setReceiptsView(receiptsList);

        setSelectedCategory(category);
    }

The Category parameter inserts the next lines inside the function:

[
  {
    "id": 2,
    "name": "Candy",
  }
]

When I run this function, I get an empty Array []. I can't really figure out what I'm doing wrong. I searched on Google for like hours and I can't get it right.

CodePudding user response:

Assuming that category (the parameter) is a string, the issue is that you are attempting to get the attribute name from the string, when you should be comparing the string to the object.

Try this:

a.category.name == category;

instead of

a.category.includes(category.name)

I may be wrong aboout assuming that category is a string, please clarify by telling us what the parameter category is equal to.

CodePudding user response:

Since the param seems to be an array of objects, you need to use Array#some for comparison instead:

const receipts = [
  { "id": 1, "name": "test", "category": { "id": 1,  "name": "Cookies" } },
  { "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];

const receiptsList = receipts.filter(({ category }) => 
  categories.some(({ name }) => name === category.name)
);

console.log(receiptsList);

  • Related