I have an array which contains a list of different objects and I want to be able to re-use the same function to filter different objects and values within the same array.
My array
cocktailList = [ Object { "abv": "24", "alcoholic": "true", "strength": "medium", "type": Object { "key": 3, "label": "Medium", "value": "medium", ..., ..., }, }, Object { ... }, ]
and I’m calling a function to filter the array passing 2 parameters:
- the field I want to filter on
- the value it should filter out
This is my function and the caller
const drinkTypeHandler = (field, value) => { const selectedType = cocktailList.filter((cocktail) => cocktail.field === value); console.log(selectedType); } onPress={() => drinkTypeHandler(item.field, item.value)}
The function is picking up the “value” param fine but it is not using the “field” param I’m passing. I tried to pass it as dynamic param as follows but still no success
cocktailList.filter((cocktail) => `cocktail.${field} === ${value}`)
If I hardcode the field value it works
i.e. cocktailList.filter((cocktail) => cocktail.type.value === value)
Advertisement
Answer
To use a dynamic field name, you have to use square brackets. So you would use:
cocktailList.filter((cocktail) => cocktail[field] === value)
The issue you are going to run into is the nested key / value pairs under type
as you can’t use something like type.value
with that notation.