簡體   English   中英

如何用javascript將遞歸json重新排列成樹結構?

[英]how to rearrange recursive json into tree structure with javascript?

我想將以下JSON轉換為另一個結構。

源JSON:

  • values =包含需要按操作過濾的對象的數組==='已評論'
  • comment =具有注釋的對象,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?
  });
 data = data.values.filter(e => e.action === 'COMMENTED')
    .map(function recursion({comment}){
     return {
      text: comment.text,
      children: [...comment.comments.map(recursion), ...comment.tasks];
     };
    });

我結束了:

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM