Matt
Matt

Reputation: 921

Where am i going wrong with this array filter? Reactjs

I am mapping over some data that I am getting from a api however when i try to add the filter function i get 'currencyData.includes is not a function'

I have also tried just hard coding the array but it also still doesnt work?

I have a loading state for when i fetch data from the api which holds code from being run but i have removed it from this example as its not getting data from the api below.

The simplified version is here...

ARRAY

var items = [
        {
          "id": 1,
          "productName": "shoes",
          "productIdentifier": "CL001",
          "productDescription": "adidas kicks boir",
          "productPrice": 2000,
          "productStock": 200,
          "created_at": "2020-51-28",
          "updated_at": null
         },
        {
          "id": 2,
          "productName": "burger",
          "productIdentifier": "FD001",
          "productDescription": "charsiu berger",
          "productPrice": 2000,
          "productStock": 200,
          "created_at": "2020-51-28",
          "updated_at": null
         }
      ]
return(
   {items.filter(currencyInfo => currencyInfo.includes("FD001")).map((value, index) => {
        console.log(value)
        return(
              <h1 key={index}>{value}</h1>
              )
    })}
)

Upvotes: 0

Views: 62

Answers (2)

hyojoon
hyojoon

Reputation: 613

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. Check this Doc

But in items.filter(currencyInfo => currencyInfo.includes("FD001")), type of currencyInfo isn't array but object.

So you should use currencyInfo.productIdentifier.includes()

Upvotes: 1

Ryan Le
Ryan Le

Reputation: 8412

currencyInfo is not an array, you can not call includes on it

Here is my suggestion:

return(
   {items.filter(currencyInfo => currencyInfo.productIdentifier === "FD001").map((value, index) => {
        console.log(value)
        return(
              <h1 key={index}>{value}</h1>
              )
    })}
)

More about includes()

Upvotes: 4

Related Questions