Exploring nested JSON through recursive iteration in JavaScript

Consider this JSON data containing comments that are fetched via AJAX call:

json = 'comments': [ 
  {'id':1,'parent':0},
  {'id':2,'parent':1},
  {'id':3,'parent':2},
  {'id':4,'parent':0}]

In order to display them properly, they need to be structured as shown below:

target_object= comments: [ 
      {id:1,parent:0, children:[
        {id:2,parent:1, children: [
          {id:3,parent:2}]}]},
      {id:4,parent:0, children:[]}]

Query:

  1. What is the most effective method to achieve this structure? (Preferably using CoffeScript iterators, but JQuery/pure JS solutions are also acceptable).

Answer №1

After dedicating some time to it, I was able to resolve the issue:

target = []

recurs = (id,json,form, single = []) ->
  for com in json.comments
    if com.parent is id
      single.push com
      if !single[single.length - 1].children?
        single[single.length - 1].children = []
      shingle = single[single.length - 1].children
      recurs(com.id,json,form, shingle)
  target[0] = single if !target[1]?
  return
recurs(0, json, target)

If anyone has suggestions for improving or repurposing the code, please feel free to share! EDIT For those interested, here is a script that can be used to format comments using the method described above:

    target = $('.comments')   
recurs = (id,json,form) ->
  for com in json.comments
    if com.parent is id
      form.append($("<div class='well'>#{com.id}</div>"))
      if !form.children('.well:last-child').children('.children:last-child').length
        form.children('.well:last-child').append('<div class="children"></div>')
      shingle = form.children('.well:last-child').children('.children')
      recurs(com.id,json,shingle)
  return
recurs(0, json, target)

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

Guidance on establishing an Array data type for a field in GraphQL Type declarations

Hey there! Currently, I'm working on my Nodejs project and facing a little dilemma. Specifically, I am trying to specify the type for graphQL in the code snippet below. However, I seem to be struggling with defining a field that should have a Javascri ...

Creating JSON from variables in SQL SERVER using the FOR JSON AUTO command is a straightforward process that allows you

I'm currently working on a SQL Server 2016 query that involves: iterating through multiple rows extracting data into variables converting these variables into JSON objects for storage in the database Below is a simplified version of the code I have ...

The use of "app.use("*") appears to be triggering the function repeatedly

app.use("*", topUsers) is being invoked multiple times. The function topUsers is called repeatedly. function topUsers(req, res, next){ console.log("req.url", req.url) findMostUsefullReviewsAggregate(6) .then(function(aggregationResult){ ...

Creating a hierarchical tree structure from tabular data with JavaScript ECMAScript 6

Seeking a JavaScript algorithm utilizing ECMAScript 6 features to efficiently convert JSON table data into a JSON tree structure. This approach should not employ the traditional recursive algorithm with ES5, but rather emphasize a functional programming me ...

Is GetStaticPath in NextJS suitable for generating large amounts of static data?

On my website, I have a page dedicated to displaying information about hotels based on their unique IDs. To achieve this functionality, I utilize getStaticPath to generate paths like /hotel-info/542711, where 542711 represents the hotel's ID. However ...

Is it considered good or bad practice to use plain JavaScript objects in an AngularJS application?

Imagine needing a custom object that doesn't rely on AngularJS (such as a specific collection with unique functionalities). You could create it independently of AngularJS and simply use it in services/controllers. Alternatively, you could design it a ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

PubNub's integration of WebRTC technology allows for seamless video streaming capabilities

I've been exploring the WebRTC sdk by PubNub and so far, everything has been smooth sailing. However, I'm facing a challenge when it comes to displaying video from a client on my screen. Following their documentation and tutorials, I have writte ...

Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2. Prior to integrating the Table component, my code looked like this: companyList <script setup> import { com ...

Loop through each item in the JSON object

After making an ajax call, I receive a json object in the success callback with the following structure: {test 1: Array(2), test 2: Array(3), test 3: Array(2)} The arrays inside each key have elements that look like this: 0: {IdProduct: "1", ProductName ...

Literal Route Waypoints Guidance Service

I am currently working on an angularjs directive that utilizes the Google Maps Direction Service. In my controller, I have a getFunction that watches for changes in a scope variable. Once the scope variable changes, it triggers the calculateAndDisplayRoute ...

jQuery is successfully manipulating pagination on CodeIgniter, however, the link is being updated as well

I've been working on a HTML page called view_closing.php. It includes a table with pagination, and my aim is to ensure that the table can move to another record without refreshing the entire page, all while remaining at the same address: http://localh ...

Is it possible to utilize AJAX requests in order to create a marker on google maps that updates in real-time?

My goal is to develop an app that generates a real-time updating google map, and I have been advised that AJAX requests can help achieve this. Nevertheless, after studying the documentation, I am uncertain about how to apply this method to solve my issue ...

Having trouble with overriding an @media query for material-ui react components?

I've been trying to modify a @media CSS rule on a Material UI component, similar to the discussions on How to over-ride an @media css for a material-ui react component and Override components like MuiTab that use media queries. However, I have not bee ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

SQL command for extracting information from a JSON data structure

In my user table, I have the user_id and user_details columns. The user_details column contains JSON data in string format as follows: 1- [{"name":"question-1","value":"sachin","label":"Enter your name?"}, {"name":"question-2","value":"<a href="/ ...

Unifying and organizing query output from various models - the Rails approach

I have a JSON-rendering controller with the following code: class AppLaunchDataController < ApiController def index service_types = [] vendors = [] tariffs = [] fields = [] vendors_hash = {} service_t ...

Generate a dynamic animation by combining two images using jQuery

My attempt to animate two images is not working. I received some help on Stack Overflow but still facing issues with my CSS and HTML code. This is the code I am using: $(document).ready(function() { $(".animar").click(function() { $("#img4" ...

Strip  symbol out of json output

Currently, I am utilizing the Volley Library to parse JSON data. However, when parsing the response, it contains a certain symbol at the beginning: JSON RESPONSE : {"category":{"420":{"key":420,"label":{"420":"Acacia"},"count":"1"},"421":{"key":421 ...

Converting JSON data into a dataframe using R

New to R and encountering an issue converting a JSON file into a dataframe. The structure of the JSON file is as follows: json_file = '[{"id": "abc", "model": "honda", "date": "20190604", "cols": {"action": 15, "values": 18, "not": 29}}, {"id": "ab ...