For loop for retrieving a attribute value from response body

Hello, Below is my response body and I am trying to validate the name of section ‘Hidden Categories Section’ is retrieving through the response of GET request or not?

Response:

{
  "sessionToken": "4obXKzms1ogKAAAABQAAAAAAAAAkYmEwNTRhNzctYWIyZC00ZTZkLWJmZTctMzQ0ZjYyMWQyZjFmAQAAAANBQ0cCAAAAA0FDUAYAAAACLTEFAAAAA2VuZwAAAAA.eigFFqJ4adoFGwFEv--uOA2IldOrwkmf0dB0J0kmw50",
  "responsesIncluded": "getSectionsCategoriesItems",
  "responses": [{
    "getSectionsCategoriesItems": {
      "content": {
        "sections": [{
            "id": 8394,
            "code": "b9c6b0e2-0ea2-4ac5-b22d-4e07a151cbd9",
            "referenceCode": null,
            "name": "Flight/Weather Section",
            "internalName": "Flight/Weather Section",
            "gridFormat": "",
            "headerTitle": "<p>Flight/Weather Section</p>\n",
            "headerBody": "<p>Flight/Weather Section</p>\n",
            "relatedItemsTitle": null,
            "iconCode": "i-f-weather-1",
            "type": "CustomContent",
            "customAction": "",
            "url": null,
            "displayOrder": 0,
            "infoModules": [
              "Flights",
              "Weather"
            ],
            "categories": [],
            "imageUrl": null,
            "teasers": [],
            "analyticsTag": null,
            "hideFromWebValet": false,
            "hideFromNativeApps": false,
            "visibleToRooms": null,
            "isEncryptedUrl": false,
            "isVisibleToAllRooms": true,
            "availabilityPeriods": [],
            "availabilitySummary": {},
            "sectionOutlets": [],
            "widgetReferenceCode": null
          },
          {
            "id": 8395,
            "code": "742021b4-0970-4459-ae3a-b34e9a2d08ab",
            "referenceCode": null,
            "name": "Outlet Content Section - Order",
            "internalName": "Outlet Content Section - Order",
            "gridFormat": "",
            "headerTitle": "<p>Outlet Content Section - Order</p>\n",
            "headerBody": "<p>Outlet Content Section - Order</p>\n",
            "relatedItemsTitle": null,
            "iconCode": "i-f-ham-1",
            "type": "OutletContent",
            "customAction": "Order",
            "url": null,
            "displayOrder": 1,
            "infoModules": [],
            "categories": [],
            "imageUrl": null,
            "teasers": [],
            "analyticsTag": null,
            "hideFromWebValet": false,
            "hideFromNativeApps": false,
            "visibleToRooms": null,
            "isEncryptedUrl": false,
            "isVisibleToAllRooms": true,
            "availabilityPeriods": [],
            "availabilitySummary": {},
            "sectionOutlets": [
              "43f198ac-9597-400f-910a-75c439e5da3d"
            ],
            "widgetReferenceCode": null
          },
          {
            "id": 8398,
            "code": "1f37a609-7928-4675-b4b3-d8b0c8e8216d",
            "referenceCode": null,
            "name": "Outlet Content Section - Service",
            "internalName": "Outlet Content Section - Service",
            "gridFormat": "",
            "headerTitle": "<p>Outlet Content Section - Service</p>\n",
            "headerBody": "<p>Outlet Content Section - Service</p>\n",
            "relatedItemsTitle": null,
            "iconCode": "i-f-spa-1",
            "type": "OutletContent",
            "customAction": "Service",
            "url": null,
            "displayOrder": 3,
            "infoModules": [],
            "categories": [],
            "imageUrl": null,
            "teasers": [],
            "analyticsTag": null,
            "hideFromWebValet": false,
            "hideFromNativeApps": false,
            "visibleToRooms": null,
            "isEncryptedUrl": false,
            "isVisibleToAllRooms": true,
            "availabilityPeriods": [],
            "availabilitySummary": {},
            "sectionOutlets": [
              "489c12d7-b7d5-493e-8391-492dbdafd55c"
            ],
            "widgetReferenceCode": null
          },
          {
            "id": 8400,
            "code": "19a599f5-7801-4704-9e1f-fb5a6af96d51",
            "referenceCode": null,
            "name": "External Content Section",
            "internalName": "External Content Section",
            "gridFormat": "",
            "headerTitle": "<p>External Content Section</p>\n",
            "headerBody": "<p>External Content Section</p>\n",
            "relatedItemsTitle": null,
            "iconCode": "i-f-alarm",
            "type": "ExternalContent",
            "customAction": "",
            "url": "",
            "displayOrder": 5,
            "infoModules": [],
            "categories": [],
            "imageUrl": null,
            "teasers": [],
            "analyticsTag": null,
            "hideFromWebValet": false,
            "hideFromNativeApps": false,
            "visibleToRooms": null,
            "isEncryptedUrl": true,
            "isVisibleToAllRooms": true,
            "availabilityPeriods": [],
            "availabilitySummary": {},
            "sectionOutlets": [],
            "widgetReferenceCode": null
          },
          {
            "id": 8414,
            "code": "50820190-18b5-4fc2-8a57-a9b0f7bb39b9",
            "referenceCode": null,
            "name": "Outlet Content Section with Availability Period",
            "internalName": "Outlet Content Section with Availability Period",
            "gridFormat": "",
            "headerTitle": "<p>Outlet Content Section with Availability Period</p>\n",
            "headerBody": "<p>Outlet Content Section with Availability Period</p>\n",
            "relatedItemsTitle": null,
            "iconCode": "i-f-departure-2",
            "type": "OutletContent",
            "customAction": "Order",
            "url": null,
            "displayOrder": 7,
            "infoModules": [],
            "categories": [],
            "imageUrl": null,
            "teasers": [],
            "analyticsTag": null,
            "hideFromWebValet": false,
            "hideFromNativeApps": false,
            "visibleToRooms": null,
            "isEncryptedUrl": false,
            "isVisibleToAllRooms": true,
            "availabilityPeriods": [],
            "availabilitySummary": {},
            "sectionOutlets": [
              "404f57ea-7ff3-4eb1-b360-ac54c3dec4f7"
            ],
            "widgetReferenceCode": null
          },
          {
            "id": 8591,
            "code": "34f41c42-2adf-4a9d-bda4-f5c6be90d9c4",
            "referenceCode": null,
            "name": "Dynamic Widget Section Visible to all",
            "internalName": "Dynamic Widget Section Visible to all",
            "gridFormat": "",
            "headerTitle": "<p>Dynamic Widget Section Visible to all</p>\n",
            "headerBody": "<p>Dynamic Widget Section Visible to all</p>\n",
            "relatedItemsTitle": null,
            "iconCode": "i-f-pin-1",
            "type": "StandardContent",
            "customAction": "",
            "url": null,
            "displayOrder": 9,
            "infoModules": [],
            "categories": [{
              "subCategories": [],
              "imageUrl": null,
              "headerTitle": "<p>Order Category</p>\r\n",
              "headerBody": "<p>Order Category</p>\r\n",
              "type": "StandardContent",
              "displayOrder": 0,
              "externalUrl": null,
              "gridFormat": null,
              "fbDisplayType": null,
              "name": "Order Category",
              "relatedItemsTitle": null,
              "updateDate": "2019-03-19T08:57:00.4501121Z",
              "sectionCode": "34f41c42-2adf-4a9d-bda4-f5c6be90d9c4",
              "code": "76864660-ea10-4120-b7ba-fcc52cb8bc5f",
              "useGallery": false,
              "categoryExtraCharges": [],
              "teasers": [],
              "analyticsTag": null
            }],
            "imageUrl": "https://irisv4neuqaasstore.blob.core.windows.net/fileresources/public/iris/ACG/beverages-250x250a6cc3b2c67d84654b849cb05a55d8944.jpg",
            "teasers": [],
            "analyticsTag": null,
            "hideFromWebValet": false,
            "hideFromNativeApps": false,
            "visibleToRooms": null,
            "isEncryptedUrl": false,
            "isVisibleToAllRooms": true,
            "availabilityPeriods": [],
            "availabilitySummary": {},
            "sectionOutlets": [],
            "widgetReferenceCode": "97ed3b44-5ed1-4d34-b53d-26161494e1b5"
          }
        ]
      }
    }
  }]
}

And I have written the below code in “Tests” where I am getting an error:"There was an error in evaluating the test script: TypeError: Cannot read property ‘name’ of undefined".

Code snippet in Tests:

 var jsonData = JSON.parse(responseBody),
    i,
    length = 100;

 for (i = 0; i < length; i++) {
     var sectionName = jsonData.responses[0].getSectionsCategoriesItems.content.sections[i].name;
     if (sectionName == "Hidden Categories Section")
         console.log("Test case Failed - Hidden category is retrieving in response");
     else
         console.log("Test case Passed - Hidden category is not retrieving in response")
 }

could you please help me

@rajshrees
This happened because you’re running a for loop 100 times and then you’re trying to access the i-th item of the array whereas your array probably doesn’t even have those items.

So, for example your sections array is of the length 10 but your for loop is checking sections[88] which is undefined and then you’re trying to access the name property of this undefined value.
That’s why you were getting the error.

Steps to fix :

  1. You can make use of safe extraction by using _.get which has been provided as a function by lodash. (lodash comes built-in with Postman)
    Docs: https://lodash.com/docs/4.17.11#get

  2. Don’t run the for loop for 100 times, just run it over all the items that you have in the sections array.

You can update your test script like this:

 var jsonData = JSON.parse(responseBody),
    i,
    // Extract out the sections array from the response that was recevied
    sections = _.get(jsonData, 'responses[0].getSectionsCategoriesItems.content.sections');

 // Run the for loop only over the items of the section, i.e uptil the section.length
 for (i = 0; i < sections.length; i++) {
     var sectionName = _.get(sections, `${i}.name`); // Safe extraction
     if (sectionName === "Hidden Categories Section") // use === instead of ==
         console.log("Test case Failed - Hidden category is retrieving in response");
     else
         console.log("Test case Passed - Hidden category is not retrieving in response")
 }
1 Like

Thanks a lot @sivcan. It helped a lot.