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

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...

creating a div that functions similarly to a radio button

Is it possible to create a div that mimics the behavior of a radio button? I'm looking for a solution that doesn't involve jquery, as many people have recommended. After doing some research, I found a few potential options. In the past, I'v ...

Using AJAX to Post Data with Relative Path in ASP.NET MVC 5

I have been developing an MVC 5 web application that utilizes AJAX Posts to invoke Controller Actions. For example, I have a controller named "Account" with an action called "Create". In my Account/Index view, which is rendered by accessing an Account/Ind ...

What causes the inconsistency in results between the geocode API and Google Maps?

I am just starting to explore the world of google geocode API and would like to utilize the free version to retrieve map coordinates for nearby golf courses. I decided to begin with my home course: http://maps.google.com/maps/api/geocode/json?address=Karls ...

Switching a class component to a functional component with react hooks (specifically useRef) - tips for preventing the dreaded "undefined" error

I have a code snippet that works as a class component and I'm trying to convert it into a functional component using the react-rewards library. Class component (working): import { Checkbox } from "@chakra-ui/react"; import React, { Compone ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

Error encountered when trying to parse a URL containing Arabic characters

I've been attempting to use a web service to translate Arabic text to English, but I keep encountering an error while constructing the URL. I have defined two possible cases for errors: enum MyErrors: Error { case urlParsingError(String) case ...

javascript for accessing JSON data both forwards and backwards

I am attempting to implement Next/Previous buttons for a json array, but I am encountering difficulties in making it work. Here is my latest attempt: <div id="text"></div> <button name="prev">go to previous div</button> <but ...

Issue with Lazy Loading in Angular 4 Universal

I recently created a new Angular CLI project to delve into server-side rendering with Angular Universal. Everything was set up and running smoothly, until I decided to implement lazy-loading for a module named 'lazy'. After implementing lazy-lo ...

Guide on incorporating the ":gt" filter from sizzle into vanilla javascript

I am currently working on adapting a jQuery plugin to be compatible with the AngularJS JQlite API, but I have encountered some challenges along the way. Here is an overview of the plugin: (function (e) { var $product = $('#product'), ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

redux - managing asynchronous storage using key-value pairs

Utilizing associative arrays with redux and storing them in async storage for later retrieval is my current challenge. When using redux, I am able to quickly access the values and efficiently map the content into cards in my react native app. However, aft ...

Converting a JSON PHP array into Javascript

How can I convert this PHP array named $data into JSON using json_encode? Whenever I try to do so in JavaScript by writing... var myJson = <?php echo json_encode($data) ?>; console.log(myJson); I encounter errors. I am curious about any restrictio ...

Employing CSS animations to elevate div elements

Currently, I am working on animating a table of divs and trying to achieve an effect where a new div enters and "bumps up" the existing ones. In my current setup, Message i3 is overlapping Message 2 instead of bumping it up. How can I make Messages 1 and 2 ...

Error Code 0: Unofficial Pandora API Issue

Working on a client for the JSON Pandora unofficial API, I encountered error code 0 during login attempts. Initially obtaining the partnerAuthToken with auth.partnerLogin, I decrypted the syncTime and stored the offset from the current system time. The req ...

The method mongoose.connect() is not defined

Having a bit of trouble connecting to my MongoDB using Mongoose - keep getting this error. const { mongoose } = require('mongoose'); const db = 'dburl.com/db' mongoose.connect(db, { useNewUrlParser: true }) .then(() => console ...

Comparing the use of jQuery click event with the button to trigger a function that calculates the

Currently, I am grappling with a JQuery function that checks if any checkboxes are ticked within my form. My version of JQuery is v1.10.2. The code functions as expected when triggered by a button, but when I attempt to trigger it with a checkbox within t ...

Unable to present the item on SwipeFlingAdapterView

I have integrated the SwipeFlingAdapterView in my project to fetch data from a MySQL database. Here are the variables defined: private ArrayList<String> al; private ArrayAdapter<String> arrayAdapter; private int i; SwipeFlingAdapt ...

Looking to minify a JavaScript file? Consider changing the overly long variable name "veryLoooooooongVariable" to something shorter,

When working on improving readability, I tend to use very long variable names which can increase the size of my JS files. I'm wondering if there are any tools or libraries available that can automatically change these long names to shorter ones? I am ...