Anthony Gorry
Anthony Gorry

Reputation: 1

Filtering results of an Array

im making an app using react-native and i am getting an array from an api. It has multiple objects in it like the one below I am trying to filter all the objects into categories.

Object {
"artists": Array [
  "A",
  "J",
  "At",
],
"average_user_rating": 4,
"categories": Array [
  Object {
    "id": "KUBdKCFGwV",
  },
  Object {
    "id": "ZTNeo8TEIO",
  },
  Object {
    "id": "O0ogwzULe8",
  },
],
"description": "", 
 },

im trying to filter it using the below code but i have been unsucsesful

    category = "KUBdKCFGwV"
        const filterCate = (category) => {
            return results.filter(result => {
                 if (result.categories.includes(category)) return result.categories;
        })

    };

Upvotes: 0

Views: 64

Answers (2)

Barmar
Barmar

Reputation: 780974

Since the categories property is an array of objects, you need to compare their id properties. You can use the some() method to test if any of the categories match the desired one.

const filterCate = (category) => results.filter(result => result.categories.some(cat => cat.id == category));

Upvotes: 1

symlink
symlink

Reputation: 12209

You were trying to filter an object, which the filter function can't do. Try filtering results.categories, and check to see if the category id matches the filterCate parameter:

const results = {
    "artists": [
      "A",
      "J",
      "At",
    ],
    "average_user_rating": 4,
    "categories": [
      {
        "id": "KUBdKCFGwV",
      },
      {
        "id": "ZTNeo8TEIO",
      },
      {
        "id": "O0ogwzULe8",
      },
    ],
    "description": "",
};

const category = "KUBdKCFGwV"
const filterCate = (category) => {
  return results.categories.filter(cats => {
    if (cats.id.includes(category)) return cats.id;
  })
};

console.log(filterCate(category));

Upvotes: 0

Related Questions