Refining an array of objects in pre-request scripts

My question:

Hi everybody,
I need your help.

By calling a GET API through Postman, I get an array of objects like this (it’s just an anonymized example, the actual objects are much longer):

[
{
“id”: “123456789”,
“name”: “Paul”,
“surname”: “Green”,
“country”: “Germany”
},
{
“id”: “987654321”,
“name”: “Mary”,
“surname”: “Jane”,
“country”: “France”
},
{
“id”: “192837465”,
“name”: “John”,
“surname”: “White”,
“country”: “Spain”
}
]

What I need is to:

  1. store the whole array of objects into a collection variable (say, “wholeResponse”);
  2. create a pre-request script in the subsequent POST call, so that it will pass a refined array of objects (containing only, say, “id” and “country”).

In the next POST call, the request body should look like this:

[
{
“id”: “123456789”,
“country”: “Germany”
},
{
“id”: “987654321”,
“country”: “France”
},
{
“id”: “192837465”,
“country”: “Spain”
}
]

I’ve already tried:

I’ve managed to accomplish step 1, i.e. to tailor a test script (concurrent with the GET) which stores the whole array of objects into a variable:

let responseData = pm.response.json();
pm.collectionVariables.set(‘wholeResponse’,JSON.stringify(responseData));

But after doing this, I have no idea how to refine the array I have stored for subsequent use.

Any help from your side would be highly appreciated, thank you in advance! :slight_smile:

Another viable option could be to store into the variable, from the very beginning (when I run the GET), just the data I want to reuse.

I found here a test script filtering the subset from JSON response (nested array), and i adapted it as follows:

var resp = pm.response.json();
subset = [];
pm.collectionVariables.set(“refinedData”, subset);
for (i=0;i<resp.length;i++)
{
var subsetData = _.pick(resp[i], [‘id’,‘country’]);
console.log(subsetData);

}

The problem is that, although I do find the results filtered in the console log, nothing is being saved into the variable “refinedData”.
Why? How could I have the script store the filtered data into my variable?

Thank you for any suggestion you can provide.