Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values in an array of JSON objects

I have an array of JSON objects like so:

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

I want to loop through them and echo them out in a list. How can I do it?

like image 740
tarnfeld Avatar asked Dec 10 '25 04:12

tarnfeld


2 Answers

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
         }
     }
 }
like image 99
Matt Greer Avatar answered Dec 12 '25 19:12

Matt Greer


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]);
    }
}
like image 42
vsync Avatar answered Dec 12 '25 19:12

vsync



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!