2017-12-30 25 views
0

次のJSONを別の構造に変換したいと思います。再帰的なjsonをjavascriptでツリー構造に並べ替える方法は?

ソースJSON:

  • 値=オブジェクトと配列が作用によってフィルタリングする必要がWICH ===は
  • コメント=コメント付きオブジェクト、Nタスクを 'コメント' 及びn
  • コメントをコメント無限より多くのコメントとタスク

{ 
    "values": [ 
    { 
     "action": "COMMENTED", 
     "comment": { 
     "text": "comment text", 
     "comments": [ 
      { 
      "text": "reply text", 
      "comments": [], 
      "tasks": [] 
      } 
     ], 
     "tasks": [ 
      { 
      "text": "task text", 
      "state": "RESOLVED" 
      } 
     ] 
     } 
    } 
    ] 
} 
を持つことができますオブジェクト
    • アレイ(複数可)各コメントまたはタスクが "子供"(再帰的!)

    [ 
        { 
        "text": "comment text", 
        "children": [ 
         { 
         "text": "reply text", 
         "type": "comment" 
         }, 
         { 
         "text": "task text", 
         "state": "RESOLVED" 
         } 
        ] 
        } 
    ] 
    

    です:

    ターゲットJSON

    IVEのユーザー:

    data = data.values.filter((e)=>{ 
        return e.action === 'COMMENTED'; 
        }).map((e)=>{ 
         // hmmm recursion needed, how to solve? 
        }); 
    
  • 答えて

    0

    私は終わった:

    let data = response.data.values 
    .filter(e => e.action === 'COMMENTED') 
    .map(function e({comment, commentAnchor}) { 
    
        return { 
        commentAnchor, 
        text: comment.text, 
        children: [...comment.comments.map(function recursion(comment) { 
    
         if (typeof comment === 'undefined') { 
         return {}; 
         } 
    
         let children = []; 
    
         if (comment.comments) { 
         children.push(...comment.comments.map(recursion)); 
         } 
    
         if (comment.tasks) { 
         children.push(...comment.tasks); 
         } 
    
         let _return = { 
         ...comment, 
         text: comment.text 
         }; 
    
         _return.children = children; 
    
         return _return; 
    
        }), ...comment.tasks] 
        } 
    

    });

    2
    data = data.values.filter(e => e.action === 'COMMENTED') 
        .map(function recursion({comment}){ 
        return { 
         text: comment.text, 
         children: [...comment.comments.map(recursion), ...comment.tasks]; 
        }; 
        }); 
    
    関連する問題