Problem with Objects

Pen to test

I try to construct an array of objects,but something goes wrong. The question is, when i consolelog that array, I see that all elements have the expected properties with the correspondent values but when I try to access them they are undefined.

online = accounts.filter(function(account) {
console.log(account); // DEBUG
console.log(account.status); // DEBUG
return account.status == 'on';

console.log(account) ->


console.log(account.status) ->

@alphaoliveira What you are experienced is a timing problem xD.

When you do the console.log(account), can you see that there is a small blue i next to the element?? That means that this object is filled at somepoint in the future because it comes from a request.

Try to do:
setTimeout(function () { console.log(account.status) }, 10);

you will see that now you can access the object.

What I suggest to do is to do whatever action you want with the response inside the function where you treated the API response.

Hope it helps!!

1 Like

Thanks. I was suspecting that was something like that. Is there another solution? I choose this one to simplify the code to build the html using Javascript. Do you think Promises are suitable to this kind of problems?

I love to work with promises. It makes everything more clear and I think that there are more friendly for the developer but I usually work with angular and there are promises everywhere :smiley:

It is going to take you some time but it will be worth it, so try it and ask if you need help!!

1 Like