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

Uncover the contents of a JSON array by employing generics and leveraging the power of

I'm currently working on an app to gain a better understanding of using generics in Swift. To achieve this, I decided to utilize Studio Ghibli's API Here's my approach: Send a request to the API Receive the response Parse the JSON data T ...

The value in a JSON can alternate between being a string or an object at times

I am facing a challenge with JSON data that can have two different formats. In one format, the location value is a string, while in the other format it is an object. Here is an example of the first format: { "result": [ { "upon_approval": "Pro ...

JSON appears to be failing to be identified

I am encountering difficulties in getting my JSON data to display correctly on my web page. Even though I have validated the JSON returned from the server and confirmed its correctness, my javascript function seems unable to process it as intended. Here is ...

A guide on adding an onClick listener to a span element dynamically and then saving it to MongoDB

I have been attempting to add an onClick event within a span tag as shown below, with the goal of storing it in MongoDb. However, my event does not seem to be saving and is automatically removed. When I retrieve data from the database, it is not present. H ...

Even though I have the image button's ID, I am unable to successfully click on it

I am facing an issue where I can't seem to click on an image button even though I know its ID: driver.findElement(By.id("its Id")).click() Unfortunately, I cannot provide the website link as it is not a public website. However, I have pasted the HTM ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

What is the best way to retrieve a document from a collection in a Meteor application?

My experience with mongodb is very limited, so I need help on how to retrieve a document from a meteor collection. I am trying to check if a document exists for the user and update it with an object. if (Saves.find({_id: Meteor.userId()}).fetc ...

Transfer the index of a for loop to another function

Can you explain how to pass the 'i' value of a for loop to a different function? I want to create a click function that changes the left position of a <ul> element. Each click should use values stored in an array based on their index posi ...

Tips for utilizing the getServerSideProps function

I want to improve the SEO friendliness of my page by utilizing the getServerSideProps method. Despite searching online, I couldn't find a specific example that fits my situation. I am uncertain about how to proceed since I currently have a useEffect m ...

ID could not be retrieved from the checkbox

I am facing an issue with my HTML checkboxes. The ids are generated from an angular ng-repeat, but when I try to collect the id for use, it always returns as undefined. $("input:checkbox.time-check-input").each(function () { var ruleUnformatted = ""; ...

Can I create interactive stacked shapes with CSS and/or JavaScript?

Trying to explain this may be a challenge, so please bear with me. I need to create an "upvote" feature for a website. The number of upvotes is adjustable in the system settings. The upvote controls should resemble green chevrons pointing upwards. For exa ...

The compatibility between JSON and the CORS header 'Access-Control-Allow-Origin' is crucial

I am trying to obtain the value from a JSON file that is located on the server. To retrieve this value, I am using AJAX. However, when checking the console for errors, I receive the following message: Cross-Origin Request Blocked: The Same Origin Poli ...

Guide on transferring a JSON array from a RecyclerView to a different activity

I am struggling to display the JsonArray data in a list view retrieved from MainActivity RecyclerView using Volley and passed to another activity. Essentially, my MainActivity contains a recyclerView, and when I click on an item in the recyclerView, I rece ...

Access your Vue.js application using Google Sign-In (GIS)

Having trouble with the discontinuation of gapi.oauth2 by Google and finding the new Sign in With Google tools confusing. Project Structure Looking to implement user sign-in with Google on my Vue frontend and authenticate them using OIDC server flow on ...

Comparing nestableSortable with the Nestable JavaScript library

I am in the process of developing a navigation menu editor that consists of multiple nested, sortable forms. My goal is to submit all the form data in one comprehensive JSON data blob. After researching, I have narrowed down my options to two libraries: n ...

Issue with Magnific Popup lightbox functionality, and mfp-hide is ineffective

Hello everyone, I am new to stackoverflow so please bear with me as I navigate through it. Although I am still a beginner in HTML, CSS, and JS, I have been using them for work on occasion. Recently, I implemented Magnific Popup on a website I am working o ...

The Ajax success callback unexpectedly displays the number "1" in the top left corner of the empty page instead of updating the specified div

Currently, I am in the process of developing a Yii2 application. I have encountered an issue where I select data from a Bootstrap modal popup and submit it to a controller action that contains an insert query. The problem arises after submitting the data f ...

Encountered an error while attempting a GET request to 'http://localhost:3000/': The resource failed to load, resulting in a net::ERR_CONNECTION_REFUSED error in delete.js

Every time I attempt to GET '/' through my express server, I encounter an error message indicating "Failed to load resource: net::ERR_CONNECTION_REFUSED ... delete.js". This issue typically arises when I try to submit a form from http://localhost ...

JavaScript is utilized to update HTML content through an Ajax request, but unfortunately, the styling is

Apologies for the unconventional title, I am currently in the process of creating a website. When the page is initially loaded, I call upon two scripts within the 'head' tag to create an attractive dynamic button effect. <script src="https:// ...

Error: The function sort cannot be applied to the result of calling the calendar method on the moment object

I retrieve the data from this URL. I am looking to display the data sorted by a recent date. I attempted to use the map method to render the data and then proceeded to sort it based on the date, but encountered an error. To organize the dates, I made use ...