在父子层次结构中显示JSON数据 [英] Display the JSON data in parent-child hierarchical structure
本文介绍了在父子层次结构中显示JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们希望在父子层次结构中显示JSON数据
We want to display the JSON data in parent-child hierarchical structure
var JsonArr = [{
"comment":"Comment 1",
"commentID":1,
"parentID":0,
"children":[{
"comment":"Comment 1-2",
"commentID":2,
"parentID":1,
"children":[{
"comment":"Comment 1-2-2",
"commentID":1,
"parentID":2
}]
}]
},
{
"comment":"Comment 2",
"commentID":4,
"parentID":0
}]
当前输出:
Current Output :
预期输出:
Expected Output :
工作JSFiddle:
https://jsfiddle.net/6dcdbks4/
Working JSFiddle : https://jsfiddle.net/6dcdbks4/
任何即时帮助将是高度赞赏。谢谢。
Any Immediate help will be highly appreciable. Thanks.
推荐答案
检查这个小提琴。
不完全是树
结构,但我们可以使用<$ c $来模仿它c> css 并传递传递级别
信息
not exactly a tree
structure but we can mimic it using css
and passing passing level
information
function showComments(comments,level){//Extra parameter for level information
for(var i = 0; i < comments.length; i++) {
commentsContainer = loadComment(comments[i], commentsContainer,level)//render comment along with level information
if (comments[i]['children'] && comments[i]['children'].length) {
showComments(comments[i]['children'],level+1)//next level for children
}
}
}
function loadComment(commentObj, commentsContainer,level){//level of node
var profileFullName = "Rohit Jindal";
//add some padding multiplied with level for each comment element
var commentHTML = '<div class="commentbox" style="padding-left:'+(level*100)+'px;"><div class="commentphoto"><a href="#123"><img src="https://graph.facebook.com/100000816365798/picture?type=square"></a></div><div class="commentcontent"><a href="#123"><strong>' + profileFullName + '</strong></a> <small>Just now</small><br>' + commentObj.comment + '<br><a name="replyComment" commentid="' + commentObj.commentID + '">Reply</a><span id="votescore-' + commentObj.commentID + '" class="votescore"></span></div></div>';
commentsContainer.append(commentHTML);
return commentsContainer;
}
showComments(JsonArr,0);//call showComment with initial level 0
这篇关于在父子层次结构中显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文