空手道API:将两个数组转换成一个对象

时间:2018-11-21 03:02:48

标签: karate

如何将以下数组合并到Karate API中的对象中。我在下面的代码中尝试了它不起作用。

键= ['foo','bar','qux'] 值= ['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

预期是这样

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

1 个答案:

答案 0 :(得分:1)

这可能有效,

* 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;
}