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

Mapping nested JSON via recursive iteration in Javascript

本文关键字:映射 嵌套 JSON 迭代 递归 Javascript 通过      更新时间:2023-11-30

想象一下这个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也可以)

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

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)