Search code examples
jqueryreplaceiterationeachjquery-templates

How to do a each inside a each in jquery?


I have this json object :

{
"msg_id":"134",
"message":"Dick",
"comment":[
    {
    "com_id":"9",
    "comment":"test",
    "msg_id":"134",
    },
    {
    "com_id":"10",
    "comment":"testtt",
    "msg_id":"134",
    },
    {
    "com_id":"11",
    "comment":"testtttt",
    "msg_id":"134",
    }]
},
{
"msg_id":"134",
"message":"Dick",
},
{
"msg_id":"134",
"message":"Dick",
}

And I'm trying to iterate through it twice. Once for the main json object and then for the comment one.

I tried this:

$.each(data, function(index, obj){
    msg += template.replace( /{{message}}/ig  , obj.message )
                   .replace( /{{msg_id}}/ig   , obj.msg_id );

    $.each(obj.comment, function(key, val){
            msg += template.replace( /{{comment}}/ig , val.comment )
                   .replace( /{{com_id}}/ig , val.com_id )
                   .replace( /{{msg_id}}/ig , val.msg_id );           
    });   
});

If I do this I get a is undefined jquery.js line 2. Maybe I need to create another function for the second loop.


Solution

  • Probably just a obj.comment being undefined (note that you don't have any comments in the last two messages), add this:

    if(obj.comment) {
    }
    

    around the inner .each call, i.e. make it something like this:

    $.each(messages, function(i, msg) {
        if(msg.comment) {
            $.each(msg.comment, function(i, comment) {
                $('#log').append($('<div>').text(comment.comment));
            });
        }
    });
    

    Working example: