buildTree 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
buildCommentTree = (data )->
# main = x for x in data when not x.parent?
main = data.filter (x) -> not x.parent?
comments_by_id = {}
for obj in data when obj.id?
comments_by_id[obj.id] = obj
recursiveFetchChilds = (chields) ->
if chields.length == 0
return
level = []
for x in chields
comment = comments_by_id[x]
if comment.chields.length > 0
chields_of_child = recursiveFetchChilds comment.chields
comment.chields = null
if chields_of_child
comment.chields = chields_of_child
level.push comment
level
result = []
for comment in main
chield_comments = recursiveFetchChilds comment.chields
comment.chields = null
if chield_comments
comment.chields = chield_comments
result.push comment
result