[英]Mapping nested JSON via recursive iteration in Javascript
想象一下這個JSON有評論並通過AJAX收到:
json = 'comments': [
{'id':1,'parent':0},
{'id':2,'parent':1},
{'id':3,'parent':2},
{'id':4,'parent':0}]
要渲染它們,我需要將它們映射如下:
target_object= comments: [
{id:1,parent:0, children:[
{id:2,parent:1, children: [
{id:3,parent:2}]}]},
{id:4,parent:0, children:[]}]
好吧,花一些時間我終於解決了它:
target = []
recurs = (id,json,form, single = []) ->
for com in json.comments
if com.parent is id
single.push com
if !single[single.length - 1].children?
single[single.length - 1].children = []
shingle = single[single.length - 1].children
recurs(com.id,json,form, shingle)
target[0] = single if !target[1]?
return
recurs(0, json, target)
如果有人可以重新考慮代碼或給予和建議,很高興聽到! 編輯也許有人會發現它很有用,下面是通過上述方法格式化注釋的腳本:
target = $('.comments')
recurs = (id,json,form) ->
for com in json.comments
if com.parent is id
form.append($("<div class='well'>#{com.id}</div>"))
if !form.children('.well:last-child').children('.children:last-child').length
form.children('.well:last-child').append('<div class="children"></div>')
shingle = form.children('.well:last-child').children('.children')
recurs(com.id,json,shingle)
return
recurs(0, json, target)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.