What is the most efficient way to organize JSON data in a tree structure using JavaScript?

I have a JSON data structure that I need to transform into a different format.

The original JSON format:

  • values = an array containing objects that need to be filtered by action === 'commented'
  • comment = an object with the comment, n Tasks, and n Comments
  • Comments can have an unlimited number of nested Comments and Tasks

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

The desired Target JSON format:

  • Arrays with Objects
  • each comment or task is a "children" (recursive!)

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

I have started working on it using the following code snippet:

data = data.values.filter((e)=>{
    return e.action === 'COMMENTED';
  }).map((e)=>{
      // Need to implement recursion here, any ideas?
  });

Answer №1

 newData = data.values.filter(entry => entry.action === 'COMMENTED')
    .map(function parse({entry}){
     return {
      description: entry.comment.text,
      replies: [...entry.comment.comments.map(parse), ...entry.comment.tasks];
     };
    });

Answer №2

Here is what I came up with:

const extractedData = response.data.values
.filter(entry => entry.action === 'COMMENTED')
.map(({comment, commentAnchor}) => {
  return {
    commentAnchor,
    text: comment.text,
    children: [...comment.comments.map(function recurse(comment) {

      if (typeof comment === 'undefined') {
        return {};
      }

      let children = [];

      if (comment.comments) {
        children.push(...comment.comments.map(recurse));
      }

      if (comment.tasks) {
        children.push(...comment.tasks);
      }

      let result = {
        ...comment,
        text: comment.text
      };

      result.children = children;

      return result;

    }), ...comment.tasks]
  }

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a spray to parse a JSON array with nested JSON elements

I have a case class with string list fields and I am struggling to parse it from JSON. I have defined a JSON Reader : val jsonReader = new JsonReader[PeaceWatcherReport] { override def read(json: JsValue): PeaceWatcherReport = { val fields = js ...

Executing Javascript code that has been retrieved using the XMLHttpRequest method in a

Would it be feasible to modify this code to function recursively if the redirects to the js file that needs to be executed? function loadScript(scriptUrl) { var xhr = new XMLHttpRequest(); xhr.open("GET", scriptUrl); xhr.onready ...

scrollable material ui chips list with navigation arrows

I'm attempting to create a unique scrollable chips array using Material UI version 4 (not version 5). Previous examples demonstrate similar functionality: View Demo Code I would like to update the scrolling bar of this component to include l ...

Transferring information to the specified link using AJAX and PHP

I'm having trouble sending data to a link that I click on. Whenever I try, I just end up with an undefined index error in my PHP file. <a href="output.php"> Click me </a> ('a').click(function(){ href = "output.php"; ...

Struggling to retrieve JSON data from JSONObject on an Android device?

Currently struggling to extract string data from a jsonArray in my code. Despite having the json object with the necessary information, I am unable to retrieve the value. Here is an example of the json structure: { "lot":[ { "id":" ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

When using Sequelize, I encountered an error message from SQLite stating that the table does not exist despite having created

I am struggling to grasp the concept of how Sequelize operates and I can't figure out why I am encountering the SQLITE_ERROR: no such table: Users error even though I have created the table using sequelize.define. Here is my code: const { Sequelize, D ...

What is the best way to ensure webpacker compiled javascript only runs once the page has finished loading in a rails application

What is the best location to place window.onload for it to execute on every page within a Rails 6 application? ...

Enhancing the functionality of hidden input fields using jQuery

I'm looking to dynamically update the value of a hidden input element when a button is clicked. Here's what I have so far: Hidden Input Element: <input type="hidden" value="action" id="action" /> Buttons: <INPUT name=submit value=~#S ...

Add value to a progress bar over time until it reaches the designated timeout

I'm struggling to implement a loading bar with a fixed timeout requirement. The goal is for the bar to be completely filled within 5 seconds. While I have successfully created the HTML and CSS components, I am facing difficulty in developing the JavaS ...

"Using Java HttpServlet to send data as a Gson string, then retrieving it in JavaScript as

On the server side, I have this Java code snippet: public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json;charset=UTF-8"); resp.setHeader("Cache-Control", "no-cach ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

Is it possible to generate HTML form fields with fixed positions when using Orbeon forms?

Is there a way in Orbeon forms to position input fields at specific coordinates, relative to a background image? I currently have a paper form that fills an entire page. My goal is to use the scanned image of this form as a background and then overlay inp ...

CSS Class ID selection for selectpicker

I have two classes: selectpicker with different IDs: selected_Test_Platforms and selected_SIL_relevant I am trying to assign a preselection from an array called "availableTestPlatforms" to the selected_Test_Platforms. Currently, when I use the selector $( ...

Eliminate disparity in Woocommerce shopping cart

I have a pizza with various toppings. When the user selects "Add Toppings," they appear as drop-down options defaulted to "none." I want to hide the selected "none" options in the cart and checkout. Although I've successfully hidden them on the cart ...

Issues with Mocha's beforeEach() and done() functions not functioning as expected

I am facing an issue with my Mocha test suite. When I run the 'make test' command, I encounter the following error message: Uncaught TypeError: Object [object Object],[object Object] has no method 'done' Below is the relevant code sni ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

Techniques for transferring PHP print_r arrays to Javascript

Array ( [0] => Array ( [sno] => 1 [name] => Sivamani [contact] => 750241378 [$city] => Madurai ) ) Array ( [1] => Array ( [sno] => 2 ...

using javascript to target a specific css selector attribute

I have a CSS file with the following code: .datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4; font-size: 16px ;font-weight: normal; } Is there a way to use JavaScript to dynamically change the font size? The code below worked ...