Dillinger
Dillinger

Reputation: 1903

Can't read object property

I've this object structure (Chrome console output):

0:Object
1:Object
2:Object

This 3 object are contained in one object called response, the response object contains all data to insert in my scheduler (but this isn't important).
Now each object have this property:

appointments: Array[2]
unavailables: Array[1]

I'm interested to get the unavailables property. Not all the three object is valorized, infact the object 1 as index, contains only the appointments data, the unavailables array is empty.

Now for the first object all working fine, the object 0, for the second object object 1 as index, I perform a condition for avoid the undefined property. The last one object is the problem, infact the data returned isn't correct. If I print the object 2 as follow (outside the for):

response[2]['unavailables'][0].id_users_provider

I get this: 92 and the result is correct.
But the foreach return a wrong value, this s my code:

for(var z = 0; z < response.length; z++)
{
    if(response[z]['unavailables'][z] != undefined)
    {
         var id_operatore = response[z]['unavailables'][0].id_users_provider;
         console.log(id_operatore);
    }
}

Chrome console return:

89 89 <- this should be 92!

Other information for the iterested object:

2: Object
         appointmens: Array[1]
         unavailables: Array[1]
                      0: Object
                                id: 189
                                id_users_provider:92

What am I doing wrong?

Upvotes: 1

Views: 231

Answers (1)

Legionar
Legionar

Reputation: 7587

You have mistake in your condition in array key, change z to 0:

for(var z = 0; z < response.length; z++)
{
    if(response[z]['unavailables'][0] != undefined) // <== here
    {
         var id_operatore = response[z]['unavailables'][0].id_users_provider;
         console.log(id_operatore);
    }
}

Upvotes: 4

Related Questions