1

I am trying to make a filtered array of objects. This is the original array:

const data = [{
        "id": "80009841-C",
        "name": "Giorgio Armani Code Homme Profumo Parfum",
        "slug": "parfum/giorgio-armani/code-homme/giorgio-armani-code-homme-profumo-parfum.html",
        "brand": "Giorgio Armani",
        "type": "Parfum",
    },
  
    {
        "id": "80022496-C",
        "name": "Issey Miyake L'Eau Majeure D'Issey Eau de Toilette",
        "slug": "parfum/issey-miyake/l-eau-majeure-d-issey/issey-miyake-l-eau-majeure-d-issey-eau-de-toilette.html",
        "brand": "Issey Miyake",
        "type": "Eau de Parfum",
    }
  ]

I want to filter by type, using this code I found:

data.filter((product) => product.type.indexOf("Parfum") >= 0)

But I'm not getting what I want, the function is returning an array with both objects, because both have the word "Parfum" inside their "type" values.

Question How can I get an exact match for the values I'm trying to filter?

MrFacundo
  • 167
  • 3
  • 13

2 Answers2

0

If exact match is what you want, then simply do this:

data.filter((product) => product.type === "Parfum");
Manuel Cheța
  • 480
  • 2
  • 10
0

const data = [{
      "id": "80009841-C",
      "name": "Giorgio Armani Code Homme Profumo Parfum",
      "slug": "parfum/giorgio-armani/code-homme/giorgio-armani-code-homme-profumo-parfum.html",
      "brand": "Giorgio Armani",
      "type": "Parfum",
  },
  {
      "id": "80022496-C",
      "name": "Issey Miyake L'Eau Majeure D'Issey Eau de Toilette",
      "slug": "parfum/issey-miyake/l-eau-majeure-d-issey/issey-miyake-l-eau-majeure-d-issey-eau-de-toilette.html",
      "brand": "Issey Miyake",
      "type": "Eau de Parfum",
  }
];

const filtered = data.filter(item => item.type == "Parfum");

console.log(filtered);
JSEvgeny
  • 2,550
  • 1
  • 24
  • 38