2

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?

1
  • just to add, theres nothing special about json. its just a javascript object initialization graph.. in your example you have an array (the square brackets), with objects in it (the curly bracket syntax).. you should check out object and array literals in javascript to reveal the 'magic' Commented Jan 1, 2010 at 11:41

3 Answers 3

6

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
         }
     }
 }
Sign up to request clarification or add additional context in comments.

Comments

2
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]);
    }
}

Comments

1

Another solution:

var jsonArray = [
  { name: "Alice", text: "a" },
  { name: "Bob",   text: "b" },
  { name: "Carol", text: "c" },
  { name: "Dave",  text: "d" }
];

jsonArray.forEach(function(json){
  for(var key in json){
    var log = "Key: {0} - Value: {1}";
    log = log.replace("{0}", key); // key
    log = log.replace("{1}", json[key]); // value
    console.log(log);
  }
});

If you want to target newer browsers, you can use Objects.keys:

var jsonArray = [
  { name: "Alice", text: "a" },
  { name: "Bob",   text: "b" },
  { name: "Carol", text: "c" },
  { name: "Dave",  text: "d" }
];

jsonArray.forEach(function(json){
  Object.keys(json).forEach(function(key){
    var log = "Key: {0} - Value: {1}";
    log = log.replace("{0}", key); // key
    log = log.replace("{1}", json[key]); // value
    console.log(log);
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.