0

I've got this JSON object:

({a1:-1,a2:null, messages:[{b1:message1, b2:message2, b3:message3, ... }]}) 

How do I loop through the messages pairs using jQuery's .each (without hardcoding the b1,b2,b3,message1,message2,message3).

2
  • Side note, that's invalid JSON. Commented Sep 9, 2011 at 18:44
  • 2
    It's also worth stating that there is no such thing as a "JSON object"! JSON is by definition a string. As soon as it ceases to be a string, it's just a JavaScript object! Commented Sep 9, 2011 at 18:45

2 Answers 2

1

Assuming data is your object, you can use $.each for this.

var messages = data.messages;
$.each(messages, function(i, msg){
   $.each(msg, function(key, message){
      console.log(key+': '+message);
   });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Start by reading the reference for jQuery.each(). Here's an apt example from the reference:

$.each({ name: "John", lang: "JS" }, function(k, v) {
    alert( "Key: " + k + ", Value: " + v );
});

2 Comments

whoa you expect someone to read the documentation for something? seriously now, by nice. :)
Thanks for your response. Sometimes it just takes an example to make it click. I realize now that I needed a nested each. Very cool.

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.