2017-12-30 21 views
0

Ich möchte den folgenden JSON in eine andere Struktur transformieren.Wie rekursive json in Baumstruktur mit Javascript neu anordnen?

Die Quelle JSON:

  • Werte = array mit Objekten weichen Bedürfnisse von Aktion gefiltert === 'kommentierte'
  • comment = Objekt mit dem Kommentar, n Aufgaben und n Kommentare
  • Kommentare haben endlose mehr Kommentare und Aufgaben können

{ 
    "values": [ 
    { 
     "action": "COMMENTED", 
     "comment": { 
     "text": "comment text", 
     "comments": [ 
      { 
      "text": "reply text", 
      "comments": [], 
      "tasks": [] 
      } 
     ], 
     "tasks": [ 
      { 
      "text": "task text", 
      "state": "RESOLVED" 
      } 
     ] 
     } 
    } 
    ] 
} 

Das Ziel JSON:

  • Array (s) mit Objekten
  • jeder Kommentar oder Aufgaben ist ein "Kinder" (rekursiv!)

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

Ive begann mit:

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

Antwort

0

Ich landete mit:

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]; 
    }; 
    });