Reputation: 21
I receive a body as
"items": [
{
"itemId": "0",
"productId": "1e212fbf-cdf2-4b30-bd60-9f315f7e4dfa"
},
{
"itemId": "1",
"productId": "1e212fbf-cdf2-4b30-bd60-9f315f7e4dfa"
},
{
"itemId": "2",
"productId": "f2b5c9e9-9c79-4430-ade6-7211d6978a27"
}
{
"itemId": "3",
"productId": "cadace2b-156a-4740-9955-fc23cf6f93aa"
}
]
I'd like to extract all productId and store them as a separate collectionVariables like
orderProductId1
orderProductId2
orderProductId3
I used
pm.collectionVariables.set("orderProductId1", jsonData.items[0].productId);
pm.collectionVariables.set("orderProductId2", jsonData.items[1].productId);
I might receive a different number of itemId/ProductId, so I don't want to manually create required number of collectionVariables. I guess I need a loop?
How to create variables with different names?
I tried
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.items.length; i++)
{
pm.collectionVariables.set("orderProductId[i]", jsonData.items[i].productId);
}
but it creates only one variable orderProductId[i] and not a orderProductId1, orderProductId2, orderProductId3.
Upvotes: 2
Views: 179
Reputation: 25851
You can find that property in the obj and set it to the collection variable with something like this:
pm.response.json().items.find((obj, index) => { pm.collectionVariables.set(`productId_${index}`, obj.productId)})
Upvotes: 1