如何用JavaScript将递归JSON重新排列成树结构?

bxpogfeg  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(99)

我想把下面的JSON转换成另一种结构。
JSON源代码:

  • values =数组,其中包含需要通过action过滤的对象=== 'commented'
  • 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?
  });
332nm8kg

332nm8kg1#

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

e4eetjau2#

最后我得到了:

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

});

相关问题