Convert Karate object with properties into map

Viewed 88

How can I use karate.map to convert this:

{
  "Test1": 10,
  "Test2": 5
}

to this:

[
  {
    "key": "Test1",
    "amount": 10
  },
  {
    "key": "Test2",
    "amount": 5
  }
]

I tried the following, which did not work.

* def objectAsMap = karate.map(objects, ([token, amount]) => ({ token, amount }))
1 Answers

Here you go:

* def response = { a: 1, b: 2 }
* def pairs = []
* karate.forEach(response, (k, v) => pairs.push({ key: k, value: v}))
* match pairs == [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]

Note that JS Array operations work, so you can even do this:

* def response = { a: 1, b: 2 }
* def pairs = Object.entries(response).map(x => ({ key: x[0], value: x[1]}))
* match pairs == [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]
Related