在Javascript中通过递归迭代映射嵌套JSON

在Javascript中通过递归迭代映射嵌套JSON,javascript,json,coffeescript,iterator,nested,Javascript,Json,Coffeescript,Iterator,Nested,想象一下,这个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, childre

想象一下,这个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:[]}]
问题:
  • 实现所需目标的最有效方式是什么?(最好使用CoffeScript迭代器,但JQuery/purejs也可以)

  • 我花了一些时间终于解决了这个问题:

    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)
    
    target=$('.comments')
    递归=(id,json,form)->
    用于json.comments中的com
    如果com.parent是id
    append($(“#{com.id}”))
    如果form.children('.well:last child')。children('.children:last child')。长度
    form.children('.well:last child')。append('')
    shingle=form.children('.well:last children')。children('.children'))
    递归(com.id、json、shingle)
    回来
    递归(0,json,目标)