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

时间:2015-02-17 03:46:57

标签: 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, children: [
          {id:3,parent:2}]}]},
      {id:4,parent:0, children:[]}]

问题:

  1. 实现所需的最有效方法是什么? (最好使用CoffeScript迭代器,但JQuery / pure JS也会这样做。)

1 个答案:

答案 0 :(得分:0)

好吧,花一些时间我终于解决了它:

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)