简体   繁体   中英

Filter array based on dynamic objects and values in JS

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)

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.

You can do that with cocktail[field] :

const drinkTypeHandler = (field, value) => {       
    const selectedType = cocktailList.filter((cocktail) => cocktail[field] === value);
    console.log(selectedType); 
}

In order to access object property using a variable, you need to use dot notation

const drinkTypeHandler = (field, value) => {       
    const selectedType = cocktailList.filter((cocktail) => cocktail[field] === value);
    console.log(selectedType); 
}

You can read more about bracket and dot notation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM