Parsing JSON tree structure into a specialized JavaScript entity

Here is a JSON string representation:

{ "a1": "root", 
  "a2": "root data", 
  "children": [
    { "a1": "child 1", 
      "a2": "child 1 data", 
      "children": []
    }, 
    { "a1": "child 2", 
      "a2": "child 2 data", 
      "children": [
        { "a1": "child 3", 
          "a2": "child 3 data", 
          "children": []
        }
      ]
    }
  ]
}

I am looking to convert this JSON tree structure into a JavaScript object. The JavaScript object should be defined with the following class structure:

function MyNode(){
    this.a1 = ""
    this.a2 = ""
    this.children = []
}

Essentially, I want to parse the JSON data and create instances of type MyNode with properties a1, a2, and children. The children nodes should also be instances of MyNode with corresponding data from the JSON string.

How can I achieve this? Any guidance would be greatly appreciated.

Answer №1

To start, use JSON.parse on the given string, then implement a recursive function to build a tree structure using your custom constructor.


Additional Note:

var result = constructTree(json);
    console.log(result);

    function constructTree(input){

       var result = new MyNode();
       result.a1 = input.a1;
       result.a2 = input.a2;

       for(var i in input.children){
           result.children.push(
               constructTree(input.children[i])
           );
       }
       return result;
    }

http://jsfiddle.net/zdeet6v5/1/

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

Minimize the size of your compiled JavaScript with GWT

Recently, I've noticed that the size of my compiled JavaScript is increasing more quickly than I anticipated. Just a few additional lines of Java code in my project can result in a significant increase in script size by several Kbs. Currently, my com ...

Is your AJAX request functional but failing to show any content on the screen?

Currently facing an issue with my quiz application's ajax request. The quiz progresses through questions and upon completion, is supposed to trigger a call to ajax.php for fetching information. I have confirmed that the ajax.php file is collecting all ...

Unique Menu: Challenge when adjusting the width of 5 divs upon hovering while maintaining full site width at 100%

I'm looking to create a sleek custom menu with 5 fields. I want the field under the mouse to expand in width on mouseover, while the other fields shrink in width. The issue I'm facing is that the transition effect is not smooth and the total wid ...

Failed HTTP request when trying to retrieve data from an external source

I am currently working on developing a web application that involves receiving an image and saving it to my device, then using that image as a link to another page. On my local machine where the web service is hosted, everything works perfectly and I rece ...

Tips for rounding a decimal to 3 decimal places?

I'm dealing with a variable called 'result' that holds a different decimal value each time. How can I round this number or display it to three decimal places? Here is the code snippet: var result = amount * exchangeRate1[fromCurrency] / exc ...

I find myself overwhelmed by the number of parameters required to design a REST API. Would it be acceptable to consolidate them into a single JSON object for easier management?

As I develop a REST API, one of the resources focuses on collecting basic data from the user's side. I have two key points to address: All user information should be sent to the server in just one HTTP request This includes approximately 30 differe ...

Leveraging JavaScript classes within Angular2

Incorporating a native JavaScript library into my Angular 2 project has been my latest endeavor. After building and bundling the JS file, I found myself in need of just one specific class called 'fhir' from this bundle. My approach involved creat ...

Adjusting package.json settings for an npm module

An npm package that I am using has an incorrect file path specified in its package.json. The current configuration is: "main": "./htmldiff.js", However, for it to function correctly, it should be: "main": "./src/html ...

Attempting to retrieve the value from a nested table within a table row using Jquery

<tr role="row" class="odd"> <td style="background-color:white"> <table> <tbody> <tr data-row-id="22"> <td id="pid"><input type="checkbox" class="sub_chk" value="8843" data-id="22">< ...

Fill in a text box with a chosen value from a linked drop-down menu

My database contains two tables: 1 - tbl_category 2 - tbl_shelf_place I am working towards displaying the shelf_code in a textbox based on the selected category_name from a drop-down (book_category) with a value of category_id, instead of using another ...

Adjust the size at the location of the cursor

I am having trouble understanding how to implement zoom based on mouse position using this example here: (https://stackblitz.com/edit/js-fxnmkm?file=index.js) let node, scale = 1, posX = 0, posY = 0, node = document.querySelector('.f ...

Prevent financial disagreement by utilizing jQuery carefully

While I'm sure this question has been asked in a similar form before, my searches for the $ sign did not return any results here. I have already built a large system and heavily utilized jQuery, using $ as a reference. Now, I don't want to rever ...

Unable to access component data while inside a v-for loop scope

I recently started using Vue and I'm having trouble accessing my component data within a v-for loop. After implementing the code below, I encountered this error message. TypeError: Cannot read property 'whatever' of undefined at eva ...

Troubleshooting the compatibility between ActionScript3 and JSON: struggling to find a solution for adapting the code to the keyframe

Hey, I'm currently learning actionScript and JSON but I'm having trouble with adapting the code to paste it into the keyframe. The code was sourced from: Whenever I try to compile, I get this error message: Scene 1, Layer 'AC', Frame ...

efficient json generation using rapidjson

I'm currently facing a challenge with creating a JSON object using rapidjson. I am encountering unexpected issues when trying to generate the desired output. Here is how I am constructing and populating the document: Document d; d.SetObject(); rapi ...

Using VueJs to associate boolean values with dropdowns

I am currently working on a form with a dropdown menu containing two options: "True" and "False". My goal is to save the selected value as a boolean in the form. For instance, when the user selects "True", I want the value stored as true in boolean format ...

Error: The architecture arm64 has duplicate symbols in React-Native

I am encountering an issue in my React-Native project after installing vision-camera-code-scanner. When attempting to build the project in XCode, I am faced with the following error message: duplicate symbol '_OBJC_CLASS_$_GDTCCTCompressionHelper&apos ...

Can you explain the significance of the `?` symbol before an object attribute? And why is my TypeScript file not recognizing it?

I have always utilized this particular behavior in Angular using the *ngIf directive when dealing with an object that could potentially be undefined or not the required object. <div *ngIf="object?.foo"> ... </div> Although I know that this ...

What is the best way to fill in a property for a mongoose schema?

let newPost = new Post({ content: fields.content, creator: req.user, }); newPost.save(function(error) { if(error) { res.status(501).json({ error: error }); } else { res.json({ post: newPost }); } }); The post model has a field called cr ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...