How to filter a list of maps using an external variable

情到浓时终转凉″ 提交于 2021-01-28 14:51:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!