sam
sam

Reputation: 289

Karate API : Converting two arrays into an object

How to merge to below arrays into an object in Karate API. I tried below code it is not working.

keys = ['foo', 'bar', 'qux'] values = ['1', '2', '3']

Feature: ArrayToObject
Scenario: ArrayToObject Coversion JS script

* def keys = ['foo', 'bar', 'qux']
* def values = ['1', '2', '3']

* def Arr2object =
  """
 function (keys, vals) {
     return keys.reduce(
      function(prev, val, i) {
        prev[val] = vals[i];
        return prev;
        }, {}
      );
   }
"""
* string text = Arr2object(keys, values)
* print text

Expected something like this

{
  "foo": "1",
  "bar": "2",
  "qux": "3"
}

Upvotes: 2

Views: 631

Answers (1)

Babu Sekaran
Babu Sekaran

Reputation: 4239

This might work,

* def Arr2object =
"""
function(keys,values){
    var newObj = {};
    if(keys.length == values.length){
        for (var i = 0; i <= keys.length - 1; i++) {
            newObj [keys[i]] = values[i];
        }
        return newObj;
    }
    return newObj;
}

Upvotes: 2

Related Questions