Saving an object in a response array as a collection variable

I’m trying to save one object in an array as a collection variable but got stuck because they all have the same key.

Below is the response body

I want to save the 3rd object in the data array as a collection variable

{
    "status": "success",
    "message": "Fetched successfully",
    "data": [
        {
            "id": 1,
            "code": "560",
            "name": "First object"
        },
        {
            "id": 2,
            "code": "304",
            "name": "Second object"
        },
        {
            "id": 3,
            "code": "308",
            "name": "Third object"
        },
        {
            "id": 4,
            "code": "328",
            "name": "Fourth object"
        }
]
}

Hey @gboyegatella :wave:

You can add the 3rd object by referencing that directly:

let response = pm.response.json();
pm.collectionsVariables.set('third_object', JSON.stringify(response.data[2]));

You’re getting the response data, then targeting the third data array object with [2]. It’s a zero indexed list so starts from [0].

Thank you @danny-dainton
But I only need the code (308) from that 3rd object.

I was going off that line :smiley:

Similar way of accessing that as before:

let response = pm.response.json();
pm.collectionsVariables.set('third_id', response.data[2].code);

i’m sure you could also use .find() or .filter() to get to that value but i went to quickest way.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.