How to get the all keys from nested array

I want to get all availability keys from response body under ‘Suites’ array, and need iterate the next requests as per count of the keys.

Response body -

{
    "planDescription": "",
    "errorCode": "",
    "isQualifyIdRequired": false,
    "offerType": "BBAR",
    "suites": [
        {
            "availabilityKey": "XXXX1234",
            "flexPackageCode": null,
            "rateCode": "BBAR",
            "minimumStay": 1,
            "availableRoomCount": 122,
            "nightlyRate": 1099.96,
            "suiteCode": "asda",
            "totalRate": 1099.96,
            "avgNightlyRate": 274.99,
            "sortOrder": 0,
            "flags": [],
            "startDate": "0001-01-01T00:00:00",
            "endDate": "0001-01-01T00:00:00"
        },
        {
            "availabilityKey": "XXXX12345",
            "flexPackageCode": null,
            "rateCode": "BBAR",
            "minimumStay": 1,
            "availableRoomCount": 22,
            "nightlyRate": 1099.96,
            "suiteCode": "KBSB",
            "totalRate": 1099.96,
            "avgNightlyRate": 274.99,
            "sortOrder": 1,
            "flags": [],
            "startDate": "0001-01-01T00:00:00",
            "endDate": "0001-01-01T00:00:00"
        }
    ]
}

I have tried below snippet but not getting each separate value. Can anyone please help? Thanks in advance!

pm.test("Each suite in the response body has an availability key", function () {
    pm.response.json().suites.availabilityKey.forEach(function(suite) {
        pm.expect(suite).to.have.property('availabilityKey');
        pm.environment.set("AvailabilityKeys", availabilityKey);

    });
});

Hey @milinddoiphode :wave:

You should be able to loop through that array and store those keys with something like:

let responseBody = pm.response.json(),
    availabilityKeysArray = [];

responseBody.suites.forEach(function (suite) {
    availabilityKeysArray.push(suite.availabilityKey);
});

pm.environment.set("availabilityKeysArray", JSON.stringify(availabilityKeysArray));

Would you be about to expand on the details of how those are going to be used next, it will make it easier to provide a follow up solution.

If you just want an array of the availability keys, then this can be achieved using the Lodash map function.

const response = pm.response.json();
let availabilityKeysArray = _.map(response.suites, 'availabilityKey')
console.log(availabilityKeysArray);

pm.environment.set("availabilityKeys", JSON.stringify(availabilityKeysArray));

I’m not really sure what you want to test here, but here is a simple test as a starter for 10.

let noOfSuites = response.suites.length
let noOfAvailabilityKeys = availabilityKeysArray.length

pm.test('number of suites and availability keys match', () => {
    pm.expect(noOfAvailabilityKeys).to.equal(noOfSuites);
})

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