问题
I have a list of maps like this:
[
{
"name": "Marco",
"email": "marco@gmail.com",
"age": 20
}, {
"name": "Polo",
"email": "polo@gmail.com",
"age": 25
}
]
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)
回答1:
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
Since fun
was declared after email
the variable reference works.
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.
回答2:
Nevermind, found out I can just reference the variable inside the function, like:
* def email = "polo@gmail.com"
* def filter_func = function(x){ return x.email == email }
* def list = response
* def filtered = karate.filter(list, filter_func)
来源:https://stackoverflow.com/questions/62873142/how-to-filter-a-list-of-maps-using-an-external-variable