2017-12-30 7 views
0

다음 JSON을 다른 구조로 변형하고 싶습니다.자바 스크립트로 트리 구조로 재귀 json을 재배치하는 방법?

소스 JSON :

  • 값 = 개체가 요구 느릅 나무로 배열 작용에 의해 === "주석"주석으로
  • 주석 = 오브젝트 N 태스크 및 N
  • 코멘트를 코멘트 여과 끝없는 더 댓글 및 작업

{ 
    "values": [ 
    { 
     "action": "COMMENTED", 
     "comment": { 
     "text": "comment text", 
     "comments": [ 
      { 
      "text": "reply text", 
      "comments": [], 
      "tasks": [] 
      } 
     ], 
     "tasks": [ 
      { 
      "text": "task text", 
      "state": "RESOLVED" 
      } 
     ] 
     } 
    } 
    ] 
} 
을 가질 수 있습니다

[대상 JSON : 객체

  • 각 주석 또는 작업이

    • 어레이 (들) (! 재귀)

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

    는 "어린이"입니다

    시작일 :

    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]; 
        }; 
        }); 
    
    관련 문제