Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  7] [ 7]  / answers: 1 / hits: 28207  / 12 Years ago, wed, march 21, 2012, 12:00:00

i have some json objects and some of them have some other objects inside them.



if i leave only the json obj that don't have other obj inside them and then apply the template, everything goes well, i get, in this case 3 li elements.



but if i grab the original json obj the results are a bit wired. I believe i need to do a each statement to iterate through each sub json obj from inside each main one



maybe i am a bit confuse so here is some code.



i have some json data like this:



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


and i am trying to arive at something like this:



Nick

test


testtt


testtttt



Nick
Nick



i've created a template like this:



function messagesTamplate(data)
{
$.each(data, function(index, obj)
{
msg += template.replace( /{{message}}/ig , obj.message );
if(obj.comment) {
$.each(obj.comment, function(key, val)
{
msg += template.replace( /{{comment}}/ig , val.comment );
});
}

});

return msg;
}


then i just append this to the main ul.



thanks


More From » jquery

 Answers
7

data needs to be an array (see the enclosing [])



var data = [{
msg_id: 134,
message: Nick,
comment: [{
com_id: 9,
comment: test,
}, {
com_id: 10,
comment: testtt,
}, {
com_id: 11,
comment: testtttt,
}]
}, {
msg_id: 134,
message: Nick,
}, {
msg_id: 134,
message: Nick,
}]


is just this in mustache templates:



{{#data}}         //loop through all data
{{message}} //pick out the message per iteration
{{#comment}} //loop through all comments in an iterated item
{{comment}} //pick out the comment
{{/comment}}
{{/data}}

[#86707] Monday, March 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
larrycodys

Total Points: 394
Total Questions: 93
Total Answers: 78

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;