如何使用外部变量过滤地图列表 [英] How to filter a list of maps using an external variable
问题描述
我有一个这样的地图列表:
I have a list of maps like this:
[
{
"name": "Marco",
"email": "marco@gmail.com",
"age": 20
}, {
"name": "Polo",
"email": "polo@gmail.com",
"age": 25
}
]
我只想返回电子邮件是特定条目的条目,例如polo@gmail.com
我通常会这样过滤:
And I want to return only the entry whose email is a specific one, like polo@gmail.com
I'll normally filter like this:
* def filter_func = function(x){ return x.email == "polo@gmail.com" }
* def list = response
* def filtered = karate.filter(list, filter_func)
但是电子邮件必须是变量,因为首先创建一个随机帐户,然后获取帐户列表,然后必须检查是否已添加该帐户,以后再使用它的其他参数(例如年龄).
But the email have to be a variable, because first I create a random account, then I get the list of accounts and have to check that the account was added and will use it's other parameters later, like the age.
是否可以将空手道过滤器函数与外部变量或其他策略一起使用?
变量用法如下所示(不起作用的示例):
Is there any way to use the karate filter function with an external variable, or another strategy?
The variable usage would be like this(not working example):
* def email = "polo@gmail.com"
* def filter_func = function(x, e){ return x.email == e }
* def list = response
* def filtered = karate.filter(list, email, filter_func)
推荐答案
在这里,您只需简单的JS:
Here you go, just simple JS:
* def email = "polo@gmail.com"
* def fun = function(x){ return x.email == email }
* def filtered = karate.filter(response, fun)
* print filtered
由于fun
在之后 email
被声明,因此变量引用起作用.
Since fun
was declared after email
the variable reference works.
在极少数情况下,如果该函数是较早声明的-例如当您想实现代码的重用时,请注意,您始终可以使用karate.get(name)
来获取当前存在的"代码.变量名称中的变量值.
In some rare cases, if the function was declared earlier - e.g. when you want to achieve re-use of code, note that you can always use karate.get(name)
to get the "currently existing" variable value by variable name.
这篇关于如何使用外部变量过滤地图列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!