views:

49

answers:

2

Hi, I have search and search the web and also on here.. for loops and all sorts for ways to access a json object like so:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

I want too loop through them and echo them out in a list?

+1  A: 

You mean something like this?

 var a = [
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" }
 ];

 function iter() {
     for(var i = 0; i < a.length; ++i) {
         var json = a[i];
         for(var prop in json) {
              alert(json[prop]);
                          // or myArray.push(json[prop]) or whatever you want
         }
     }
 }
Matt Greer
+1  A: 
var json = [
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

for(var i in json){
    var json2 = json[i];
    for(var j in json2){
        console.log(i+'-'+j+" : "+json2[j]);
    }
}
vsync