通过Javascript中的递归迭代映射嵌套JSON
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:[]}]
问题:
- 实现所需目标的最有效方法是什么?(最好使用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)
相关文章:
- immutable.js与嵌套映射/对象的比较/相等性能
- 有没有一种简单的方法可以用Lodash映射嵌套数据
- 挖空映射 - 使用键唯一标识嵌套对象
- 通过Javascript中的递归迭代映射嵌套JSON
- 将多个链接表映射到嵌套的JQuery手风琴
- KNOCKOUTJS 映射嵌套元素不是绑定的
- 从数组中的键遍历嵌套映射/对象
- 使用 ng 重复映射嵌套值
- 映射嵌套的 KO 视图模型
- 映射到嵌套组件的 Elm 效果
- 如何映射嵌套对象的数组
- 嵌套json的Knockout映射
- 在Immutable.js映射中查找嵌套对象的最佳方法
- Node.js automapper ts包未映射嵌套对象/属性
- 映射和绑定嵌套对象和数组
- 使用forEach、映射或筛选器克隆和操作嵌套对象,而不修改原始对象
- 如何将嵌套JSON映射到具有函数的Object结构
- 嵌套for循环和备用映射方法
- 在嵌套映射中的作用域
- 在json数据中获取嵌套映射