简体   繁体   中英

Mapping nested JSON via recursive iteration in Javascript

Imagine this JSON that has comments and received via AJAX:

json = 'comments': [ 
  {'id':1,'parent':0},
  {'id':2,'parent':1},
  {'id':3,'parent':2},
  {'id':4,'parent':0}]

To render them, I need to map them as below:

target_object= comments: [ 
      {id:1,parent:0, children:[
        {id:2,parent:1, children: [
          {id:3,parent:2}]}]},
      {id:4,parent:0, children:[]}]

Question:

  1. what is the most efficient way to achieve required? (preferably using CoffeScript iterators, but JQuery/pure JS will do too).

Well, spending some time i finally solved it:

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)

If anyone can re-factor code or give and advice, would be glad to hear! EDIT maybe someone will find it useful, below is the script for formatting comments via above method:

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM