1

I have the below json:

{
  "id": [
    "1A",
    "2B"
  ],
  "name": [
    "rs",
    "mk"
  ]
}

I want to extract the id value when name is 'rs' or 'mk'. There will be no duplication of name values and the size of id and name keys will always match.

So i have created the following scenario where:
- I iterate through the name array using forEach.
- Find if the value of name matches rs or mk and if it does, retrieve the index.
- Then use this index to find the retrieve the value from id key.

When I run this, the name_rs_idx and name_mk_idx are not being set and are blank.

Scenario: Using forEach and karate.set
    * def vals = { id: ['1A', '2B'], name: ['rs', 'mk'] }
    * def name_rs_idx = ''
    * def rsFun =
      """
        function(x, i) {
          if(x == 'rs') {
            karate.set(name_rs_idx, i);
          }
        }
      """
    * karate.forEach(vals.name, rsFun)
    * print 'RS Index - ' +  name_rs_idx
    * def name_rs_id = vals.id[name_rs_idx]
    * print 'RS id -' + name_rs_id

    * def name_mk_idx = ''
    * def mkFun =
    """
      function(x, i) {
        if(x == 'mk') {
          karate.set(name_mk_idx, i);
        }
      }
    """
    * karate.forEach(vals.name, mkFun)
    * print 'MK Index - ' + name_mk_idx
    * def name_mk_id = vals.id[name_mk_idx]
    * print 'MK id -' + name_mk_id

Maybe i am not using the forEach function correctly or logic is incorrect.

1 Answer 1

1

I think you are over-complicating things :) Here is my solution, take time to read and understand it, it will improve your Karate fundamentals ! To simplify things, we first combine the data into an array of { name: '', id: '' } pairs. Then things become much easier.

* def vals = { id: ['1A', '2B'], name: ['rs', 'mk'] }
* def fun = function(x, i){ return { name: vals.name[i], id: vals.id[i] } }
* def pairs = karate.map(vals.name, fun)
* def fun = function(x){ return x.name == 'rs' || x.name == 'mk' }
* def filtered = karate.filter(pairs, fun)
Sign up to request clarification or add additional context in comments.

2 Comments

I have a problem similar to the original poster, but in my case 'rs' and 'mk' have to be variables, I can't find any example of filter function with variables. What do you think I can do?
@MioMio ask a new question ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.