Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below:

[{
  "thread_id": 2710,
  "parent_id": "",
  "username": "string",
  "comment": "string",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 1
}, {
  "thread_id": 2710,
  "parent_id": "1",
  "username": "string2",
  "comment": "string2",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 2
}, {
  "thread_id": 2710,
  "parent_id": "",
  "username": "string32",
  "comment": "strin2g2",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 3
}, {
  "thread_id": 2710,
  "parent_id": "",
  "username": "str23ing32",
  "comment": "strrgein2g2",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 4
}, {
  "thread_id": 2710,
  "parent_id": "3",
  "username": "str2rr3ing32",
  "comment": "strr@gein2g2",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 5
}, {
  "thread_id": 2710,
  "parent_id": "3",
  "username": "str2ergergrr3ing32",
  "comment": "strr@geinergerg2g2",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 6
}, {
  "thread_id": 2710,
  "parent_id": "6",
  "username": "str2ergrrrgergergrr3ing32",
  "comment": "strr@geiergergernergerg2g2",
  "postdate": "2017-06-09T07:12:32.000Z",
  "id": 7
}]

How can I create a javascript function to restructure the Response as shown below?

{ id: 1
  parent_id: "",
  ....,
  comments: [
   {
    id: 12,
    parent_id: 1,
    comments: [{ parent_id: 12 ....}]
   }
  ]

Answer №1

To create a tree using a single loop, you can implement the standard algorithm where each node is created and connected based on its id and parent_id.

var data = [{ thread_id: 2710, parent_id: "", username: "string", comment: "string", postdate: "2017-06-09T07:12:32.000Z", id: 1 }, { thread_id: 2710, parent_id: "1", username: "string2", comment: "string2", postdate: "2017-06-09T07:12:32.000Z", id: 2 }, { thread_id: 2710, parent_id: "", username: "string32", comment: "strin2g2", postdate: "2017-06-09T07:12:32.000Z", id: 3 }, { thread_id: 2710, parent_id: "", username: "str23ing32", comment: "strrgein2g2", postdate: "2017-06-09T07:12:32.000Z", id: 4 }, { thread_id: 2710, parent_id: "3", username: "str2rr3ing32", comment: "strr@gein2g2", postdate: "2017-06-09T07:12:32.000Z", id: 5 }, { thread_id: 2710, parent_id: "3", username: "str2ergergrr3ing32", comment: "strr@geinergerg2g2", postdate: "2017-06-09T07:12:32.000Z", id: 6 }, { thread_id: 2710, parent_id: "6", username: "str2ergrrrgergergrr3ing32", comment: "strr@geiergergernergerg2g2", postdate: "2017-06-09T07:12:32.000Z", id: 7 }],tree = function (data, root) {
        var r = [],
            o = {};
        data.forEach(function (a) {
            var comments = o[a.id] && o[a.id].comments;
            if (comments) {
                a.comments = comments;
            }
            o[a.id] = a;
            if (a.parent_id === root) {
                r.push(a);
            } else {
                o[a.parent_id] = o[a.parent_id] || {};
                o[a.parent_id].comments = o[a.parent_id].comments || [];
                o[a.parent_id].comments.push(a);
            }
        });
        return r;
    }(data, '');

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Analyze discrepancies following a particular character within a string

I am in possession of two JSON input files: torrance.json austin.json Due to their extensive length, the complete content of these files cannot be displayed here. However, they adhere to the following structure: data_1 = { "accessibility-service": { ...

Receiving an empty response of "[ ]" from the PHP server that was expected to provide a JSON array

I am encountering a problem where I need to send a JSON array from a PHP and MySQL server to an Android application. Even though there are no errors in the code, it does not produce the expected output. Here is the output displayed after running the code: ...

Issue occurred: Unable to locate metadata.json file while attempting to push to openShift git

I encountered an issue while trying to deploy a second version of my nodeJS + MongoDB app on OpenShift. The initial deployment was successful, but the subsequent attempt is failing with the following error message: Erics-MacBook-Air:rippleRating ericg$ gi ...

Slower CSS rendering as Javascript finishes its tasks

I am currently dealing with a jQuery plugin that is quite large and complex, but I will not be sharing it here to keep things simple. The issue I am facing is relatively straightforward, so I will focus on the essential code snippets: There is a click eve ...

Performing JavaScript functions after fetching an XSLT page via AJAX

Is there a way to trigger JavaScript at a particular time without relying on setInterval() or onClick()? The issue I'm facing is that when I click to load an XSLT page using Ajax, the JavaScript within it does not execute even though it's writt ...

Engage the PROTRACTOR refresh function

I'm just getting started with automation and Protractor. I successfully automated the login page, but now I'm facing a challenge with accessing a menu that I need in order to navigate to a different page. Within the menu, there is an href="#/dom ...

Enhance your SQL FOR JSON query by including an additional array bracket

I've been on a long search for an answer to this question: How can I add an additional array bracket in the subselect? Here is the Query I have: select -- Images ( SELECT tMedien.WebshopID AS 'mediaId', ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Exploring the meaning behind RxJS debounce principles

Referencing information found in this source: const debouncedInput = example.debounceTime(5); const subscribe = debouncedInput.subscribe(val => { console.log(`Debounced Input: ${val}`); }); When the first keyup event occurs, will the debouncedI ...

The nodes.attr() function is invalid within the D3 Force Layout Tick Fn

I'm currently experimenting with the D3 Force Layout, and I've hit a roadblock when it comes to adding elements and restarting the calculation. Every time I try, I keep encountering this error: Uncaught TypeError: network.nodes.attr is not a fun ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

Is there a way to submit a PUT method form in Laravel seamlessly without having to refresh the page?

Below is the HTML form code used in my Laravel application: <button onclick="submitForm()">submit form using jquery ajax</button> <form name="fbCommentCountform" action="{{ route('blogs.update', ['id'=>$id]) }}"> ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

Error encountered: Unexpected token '"', expecting "}". Perspective from React : It is an unfortunate occurrence which h

I'm a newbie when it comes to React and I'm currently following a tutorial. Unfortunately, I encountered an error message while the script was trying to compile: Parsing error: Unexpected token, expected "}" The issue seems to be with the &apos ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

trouble encountered when attempting to integrate typeahead functionality in AngularJS using jQuery

Greetings! I am brand new to using AngularJS and currently exploring the implementation of typeahead functionality. I decided to utilize an existing library by including the following script: <script src="lib/xyz/typeahead.bundle.js"></script> ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Instructions for modifying the color of the close button in the angularjs ui-select module

I am currently using ui-select for multiple selection in a dropdown. When an item is selected, it displays a cross button on the upper right corner of the selected item. Is there a way to change the color of the cross button to red? <ui-select multip ...

Node.js data querying methods and best practices for code structuring

Recently delved into the world of nodejs and still fairly new to JavaScript. In my quest for best practices, I stumbled upon this helpful resource: Currently, I am working on an application following the structure recommended in the resource. The suggesti ...