Helping to correct script, error in execution

Response is easy to verify and see based on get open to public
https://petstore.swagger.io/v2/pet/findByStatus?status=available

my script

let arr = pm.response.json();

for (var i=0; i < arr.length ; i++)
{
console.log(arr[i].id);
console.log(arr[i].name);
console.log(arr[i].category);
console.log(arr[i].category.id);
console.log(arr[i].category.name);
}

Console output look correct at the start I just copied part of it output longer

9223372016900024000 
Puff
{id: 0, name: "string"}
0
string
922332016900024000 
doggie
{id: 0, name: "string"} 
0

but at the end I get error
TypeError: Cannot read properties of undefined (reading 'id')

WHY, it reads all ID’s before correctly, why would that gives error at the end? thanks for help

Hey @masusa2020 :wave:

Welcome to the Postman Community! :postman:

Could you provide some additional context for your question, please?

That petstore response returns ~670 objects which you’re iterating through to log the values from the objects to the console.

What are you trying to achieve? There are other JS methods that could be used if you want to log or use something specific from the response.

First of all thanks for taking a note to my post. I have no other purpose to script besides learning. in my Get method at least today there are only 259 objects, I used below, hope it is correct
const responseJson = pm.response.json();
var count = Object.keys(responseJson).length;
console.log("The number of expected keys in the response body is: " + count);

Only thing I need is to see how to access every single object in Array and all elements of this object do i can test for example for missing or null / 0 values when it is required to have value for example. So in my question I was puzzled how come all data gets displayed but at the end I get error
Error: Cannot read properties of undefined (reading ‘id’ ) even though I get all id’s in the beginning of script,

{
    "id": 9223372016900077000,
    "category": {
      "id": 0,
      "name": "string"
    },
    "name": "Puff",
    "photoUrls": [
      "string"
    ],
    "tags": [
      {
        "id": 0,
        "name": "string"
      }
``` When I run script like this 
for (var i=0; i < arr.length ; i++)
{
 console.log(arr[i].id);
 console.log(arr[i].name);
 console.log(arr[i].category);
 //console.log(arr[i].category.id);
 //pm.expect (arr[i].category.id).not.eql(null)
 //console.log(arr[i].category.name);
}
I have no errors, but as soon as I uncomment line
console.log(arr[i].category.id); I get error why?
if id is next element under category? 
Cant figure that out
Same goes for uncommenting
console.log(arr[i].category.name);
now i get error
TypeError: Cannot read properties of undefined (reading 'name')

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