【问题标题】:Mapping nested JSON via recursive iteration in Javascript通过 Javascript 中的递归迭代映射嵌套的 JSON
【发布时间】:2015-02-17 03:46:56
【问题描述】:

想象一下这个包含 cmets 并通过 AJAX 接收的 JSON:

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/纯 JS 也可以)。

【问题讨论】:

    标签: javascript json coffeescript iterator nested


    【解决方案1】:

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

    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)
    

    如果有人可以重构代码或提供建议,将很高兴听到! 编辑 也许有人会觉得它很有用,下面是通过上述方法格式化 cmets 的脚本:

        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)
    

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      相关资源
      最近更新 更多