Get the latest record from an array response without root

I want to get the user_recipient_id of the last node from the responseBody array.
This is dynamic, a new node from the last node will be added for new data in responseBody.

Sample responseBody:

[
    {
        "nickname": "Drew",
        "user_recipient_id": 40,
    },
    {
        "nickname": null,
        "user_recipient_id": 44,
    },
    {
        "nickname": "N3// reci",
        "user_recipient_id": 126,
    }
]

My code:

const responseJson = pm.response.json();
var i = Object.keys(responseJson).length;
console.log("The number of expected keys in the response body is: " + i)
postman.setEnvironmentVariable("i", i);

pm.environment.set("urid", responseJson.$[Number(i)].user_recipient_id);
console.log(pm.variables.get("urid"));

I’m getting a result of

TypeError: Cannot read property ‘10’ of undefined

due to Number(i) in this line pm.environment.set("urid", responseJson.$[Number(i)].user_recipient_id);
Tried to parseInt as well.

Hi @aviation-meteorologi,

As you are looking for the last index of the array, you would need to find the length of the array and -1. due to array indexing starting at 0 and not 1. So to find the last index of the array I would do something like this.

let arr = [
    {
        "nickname": "Drew",
        "user_recipient_id": 40,
    },
    {
        "nickname": null,
        "user_recipient_id": 44,
    },
    {
        "nickname": "N3// reci",
        "user_recipient_id": 126,
    }
];

let getId = arr.length -1;

console.log(arr[getId].user_recipient_id) // 126

Thank you ianb120!

got it working!

Here’s my new code

const responseJson = pm.response.json();
let arr = responseJson;
let getId = arr.length -1;
pm.environment.set("urid", arr[getId].id);
console.log(pm.variables.get("urid"));
1 Like

Excellent! Glad it’s working for you :blush: