如何用javascript将递归json重新排列成树结构?

时间:2017-12-30 14:44:37

标签: javascript json recursion

我想将以下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?
  });

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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]
  }

});