1

I would like to transform the following JSON into another structure.

The source JSON:

  • values = array with objects which needs to filtered by action === 'commented'
  • comment = object with the comment, n Tasks and n Comments
  • Comments can have endless more Comments and Tasks

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

The Target JSON:

  • Array(s) with Objects
  • each comment or tasks is a "children" (recursive!)

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

I've started with:

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

2 Answers 2

3
 data = data.values.filter(e => e.action === 'COMMENTED')
    .map(function recursion({comment}){
     return {
      text: comment.text,
      children: [...comment.comments.map(recursion), ...comment.tasks];
     };
    });
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up with:

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

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.