我正在尝试为我的网站制作类似reddit的评论。我有这个数据库结构(MySql
):
parent_id | comment_id | comment
这是来自数据库的示例数据:
var data = [
{comment_id: "1a", parent_id: "", comment: "11111"},
{comment_id: "2a", parent_id: "1a", comment: "22222"},
{comment_id: "3a", parent_id: "1a", comment: "33333"},
{comment_id: "4a", parent_id: "3a", comment: "44444"},
{comment_id: "5a", parent_id: "", comment: "55555"},
{comment_id: "6a", parent_id: "5a", comment: "6666"},
]
// if parent_id == "", it's parent.
我需要与它的孩子建立该列表关系。我做了,但我不能实现递归,所以父母只是范围first childs
。
我的实施:
function parse(arr) {
var mothers = []
//find mothers
for (var i = 0; i < arr.length; i++) {
//if parent_id == "" => it's mother.
if(arr[i].parent_id == "") {
arr[i].childs = [] // make it's childs
mothers.push(arr[i])
arr = _.without(arr, arr[i])
}
}
var childs = arr
for (var i = 0; i < childs.length; i++) {
var possibleChild = childs[i]
var parent_id = possibleChild.parent_id
for (var z = 0; z < mothers.length; z++) {
var mother = mothers[z]
if(mother.comment_id == parent_id){ // match it with mother
mother.childs.push(possibleChild)
}
}
}
return mothers
}
有人可以帮忙吗?感谢。