How to loop through a JavaScript Object?

Well, I’m fetching facebook likes by a user who has authenticated us already and checking if my page exists in it.

FB.api('/me/likes, function(response) {
	console.log(response);
});

And I get the following in console (FireFox):

data
	[Object { name="Excel in ABCD", category="Book", id="327361517327399", more...}, Object { name="LMNOPQ", category="Product/service", id="175625882542984", more...}, Object { name="UVWXYZ", category="Book", id="260641707360118", more...}, 7 more...]
	
0
	Object { name="Excel in ABCD", category="Book", id="327361517327399", more...}
	
category
	"Book"
	
created_time
	"2012-04-04T05:31:04+0000"
	
id
	"327361517327399"
	
name
	"Excel in ABCD"
	
1
	Object { name="LMNOPQ", category="Product/service", id="175625882542984", more...}
	
2
	Object { name="UVWXYZ", category="Book", id="260641707360118", more...}

I want to access name from this, so with the help of “Baptiste Pernet” I tried the following:

FB.api('/me/likes, function(response) {
    for(var i in response) {
        console.log(response[i]);//gives me another object (it is nested, check below)
    }
});

and this took me closer but not completely:

[Object { name=“Excel in ABCD”, category=“Book”, id=“327361517327399”, more…},
Object { name=“LMNOPQ”, category=“Product/service”, id=“175625882542984”, more…},
Object { name=“UVWXYZ”, category=“Book”, id=“260641707360118”, more…},

Now how do I access properties of the inner object?

Thanks

If the response is an array, the for…in statement is the correct one to use. Instead, you should us an ordinary for loop for an array.

You can also assign the item from the array to a variable, will allow you to more easily access different parts of the object.


var item,
    i;
for (i = 0; i < response.length, I += 1) {
    item = response[i];
    // access item.name, item.category, item.id, ...
}

Thanks Paul.

The following got me the desired result:

for(var i in response.data) {
  if (response.data[i].name == 'LMOPQ') {
    return true
  }
}

return false;

Regards