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.
Probably just a
obj.commentbeing undefined (note that you don’t have any comments in the last two messages), add this:around the inner
.eachcall, i.e. make it something like this:Working example: