# For loop for retrieving a attribute value from response body

**URL:** <https://community.postman.com/t/for-loop-for-retrieving-a-attribute-value-from-response-body/4613>\
**Category:** Help Hub\
**Tags:** tests, variables, collections\
**Created:** [March 19, 2019, 9:10am UTC](https://community.postman.com/t/for-loop-for-retrieving-a-attribute-value-from-response-body/4613 "2019-03-19T09:10:15Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![singhsivcan](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/singhsivcan/32/1595_2.png) [@singhsivcan](https://community.postman.com/u/singhsivcan)\
**Post date:** [March 19, 2019, 9:27am UTC](https://community.postman.com/t/for-loop-for-retrieving-a-attribute-value-from-response-body/4613/2 "2019-03-19T09:27:44Z")

</div>

@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](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:

```auto
 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")
 }

```

---

_[View the full topic](https://community.postman.com/t/for-loop-for-retrieving-a-attribute-value-from-response-body/4613)._
