[英]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:我正在调用一个函数来过滤传递 2 个参数的数组:
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.您将遇到的问题是
type
下的嵌套键/值对,因为您不能使用带有该符号的type.value
东西。
You can do that with cocktail[field]
:你可以用
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您可以在此处阅读有关括号和点符号的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.