繁体   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