Take the 2-minute tour ×

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

share|improve this question
What? What's the question? –  Zirak Sep 9 '11 at 18:39
Side note, that's invalid JSON. –  aziz punjani Sep 9 '11 at 18:44
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! –  Adam Terlson Sep 9 '11 at 18:45
add comment

2 Answers

up vote 1 down vote accepted

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);
share|improve this answer
add comment

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 );
share|improve this answer
whoa you expect someone to read the documentation for something? seriously now, by nice. :) –  Eonasdan Sep 9 '11 at 18:49
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. –  Eman Resu Dilav Sep 9 '11 at 21:45
add comment

Your Answer


