Jorge Martínez
Jorge Martínez

Reputation: 31

React Native - Search Filter

I have this data:

export const recepies = [
{
  key: '1',
  title: 'Recepie Name',
  ingredients: [
    {
      id: '1',
      name: 'pepperoni'
    },
    {
      id: '2',
      name: 'pineapple'
    }
  ]
},
{
  key: '2',
  title: 'Another recepie',
  ingredients: [
    {
      id: '1',
      name: 'apple'
    },
    {
      id: '2',
      name: 'orange'
    }
  ]
}
];

I have a filter function that receives a string from a textInput, and then I set the state with the results from that filter.

filter(text) {
    const newData = recepies.filter(function (item) {
      const itemData = item.title.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      text: text,
      data: newData,
    });
  }

Right now I can only search recepies by their 'title', how could I search recepies by any of their ingredients

Thanks for your help!

Upvotes: 0

Views: 1018

Answers (2)

Jeff Hampton
Jeff Hampton

Reputation: 66

If you're set on writing this out yourself, you'd need to handle filtering at different levels for arrays containing keys that match values, cases where keys don't exist, etc. For a simple implementation, you can modify your function to accept a key, compare using contains (.indexOf() > -1) and do a shallow filter as so:

filter(key, text) {
    const newData = recepies.filter((item) =>
      item[key].toUpperCase().indexOf(
        text.toUpperCase()
      ) > -1
    );
    this.setState({
      text: text,
      data: newData,
    });
  }

However, I'd strongly recommend using lodash or even the searchjs NPM package that will more gracefully let you search text and handle the normal error and deep-searching cases that you might need.

Upvotes: 1

Bruno Mazzardo
Bruno Mazzardo

Reputation: 1586

Try this :

   filter(text) {
        const newData = recipies.filter((recipe)=>{
          recipe.ingredients.forEach((ingredient)=>{
                 if(ingredient.name === text)
                    return true
           })
        })

   this.setState({
      text: text,
      data: newData,
    });     
}

Upvotes: 0

Related Questions