Skip to content
Advertisement

Filter in array of object inside object in Javascript

I’m trying to filter some products with the categories (by the woocommerce API) but i have a little trouble to do it. do you have the right way to do it? thanks

My array from the API :

{id: 199, name: "Dark Suit", slug: "dark-suit", permalink: "https://caisse.diliko.fr/produit/dark-suit/", date_created: "2020-08-20T10:53:06", …}
categories: Array(2)
0:
id: 30
name: "Clothing"
slug: "clothing"
__proto__: Object
1: {id: 31, name: "Men's Clothing", slug: "mens-clothing"}
length: 2
__proto__: Array(0)

And my filter function:

export const getProductsById = (products, id) => (
  
    products.filter(product => product.categories.name == id)
    );

Advertisement

Answer

Here’s what you want, I reckon. A filter that checks whether any of the categories of the product has the id you’re looking for.

products = [
{
  id: 199,
  name: "Dark Suit",
  categories: [
    {
      id: 30,
      name: "Clothing",
      slug: "clothing"
    },
    {
      id: 31,
      name: "Suits",
      slug: "suits"
    }
  ]
},
{
  id: 200,
  name: "Light Suit",
  categories: [
    {
      id: 30,
      name: "Clothing",
      slug: "clothing"
    },
    {
      id: 31,
      name: "Suits",
      slug: "suits"
    }
  ]
},
{
  id: 201,
  name: "Banana",
  categories: [
    {
      id: 2,
      name: "Fruit",
      slug: "fruit"
    },
    {
      id: 3,
      name: "Yellow",
      slug: "yellow"
    }
  ]
},
{
  id: 201,
  name: "Orange",
  categories: [
    {
      id: 2,
      name: "Fruit",
      slug: "fruit"
    },
    {
      id: 4,
      name: "Orange",
      slug: "orange"
    }
  ]
}

];

console.log(filter(31)); //suits
console.log(filter(2)); // fruit
console.log(filter(3)); // yellow

function filter(categoryId) {
  return products.filter(product=>product.categories.some(element=>element.id==categoryId));
}
Advertisement