简体   繁体   中英

How to Loop Through a JavaScript Object

I used

console.log(response);

and got the following in console (in Firebug). How do I loop through to check if "LMNOPQ" exists?

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...}

Then as suggested by Baptiste Pe.net, I tried the following:

for(var i in response) {
    console.log(response[i].name);//gives me undefined
    console.log(response[i]);//gives me another object (it is nested, check below)
}

[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...},

How do I get this name now? I'm stuck at:

console.log(response[i]);

What should I write in order to get the properties of nested objects? Another loop?

You should try to use JSON.stringify(response) and then this site to visualize the result. It is far more standard than the format you provide.

From what you gave, it seems that you have a member called data that contains an array (again, I am not sure because you didn't provide a good format to describe you javascript object).

So let's try

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

return false;

you can use

for (var prop in Object) {
    if(prop == "LMNOPQ") {
        // Do something
    }
}

or you can use if( response[like].hasOwnProperty("LMNOPQ") ) alternatively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM