How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows:

JSON Response

{
    "name":"animal",
    "state":false,
    "children":[
        {
            "name":"cats",
            "state":false,
            "children":[
                {
                    "name":"tiger",
                    "state":false,
                },
                {
                    "name":"puma",
                    "state":false,
                    "children":[
                        {
                            "name":"babyPuma",
                            "state":true
                        }
                    ]
                }
            ]
        },
        {
            "name":"dogs",
            "state":false,
            "children":[
                {
                    "name":"pitbull",
                    "state":true
                },
                {
                    "name":"german",
                    "state":false,
                    "children":[
                        {
                            "name":"shepherd",
                            "state":true
                        }
                    ]
                }
            ]
        }
    ]
}

I am using observables to fetch this data and have successfully cast the first node:

http.service.ts snippet

getTreeData(): Observable<Leaf>{  
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:8000/',{ headers: headers ...})
        .map(res =>new Leaf(res.json()));
}

Here's the Leaf class implementation:

Leaf.ts

export class Leaf{
    name: string;
    state: string;
    treeData: Array<Leaf>;


    constructor(input:any){
        this.name = input.name;
        this.state = input.state;
        this.treeData = input.children;
    }

    toggleState() {
        if (this.state=='active'){
            this.state = 'inactive';
        }
        else {
            this.state = 'active'
        }
    }
}

My end goal is to display the JSON tree in a folder-like structure. Is there a way to traverse through all nodes using map(), or do I need to implement a different approach involving a combination of map() and a traverser function?

Answer №1

To start, I would design an interface structure for the json data:

interface LeafJson {
    name: string;
    state: string;
    children?: LeafJson[];
}

After defining the interface, I would utilize Array.map to generate the child elements:

export class Leaf {
    name: string;
    state: string;
    treeData: Array<Leaf>;

    constructor(input: LeafJson){
        this.name = input.name;
        this.state = input.state;
        this.treeData = input.children ? input.children.map(item => new Leaf(item)) : [];
    }

    toggleState() {
        if (this.state=='active'){
            this.state = 'inactive';
        } else {
            this.state = 'active'
        }
    }
}

(view code in playground)

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

Get an array of JSON values using a jQuery function

How can I create a jQuery function that imports a JSON value and returns an array when called? I have written the following function, but it is returning an empty array. The JSON file I am working with is very basic, similar to this example: { "fruit": [ ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

Learning how to replace the alert function with Bootbox

I am currently working on a form that posts to a MySQL database. I want to replace the alert function triggered by the Malsup jQuery Form Plugin with the one created by the Bootbox plugin. Even though both plugins are functional, I struggle to integrate th ...

Issue: Unable to link to 'FormGroup' because it is not recognized as a valid property of 'form'

app.module.ts import { BrowserModule } from '@angular/platform-browser'; import {CUSTOM_ELEMENTS_SCHEMA, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {AppRoutes} from './app.routin ...

Using jQuery, you can enclose a string of text with HTML tags easily

This specific content within the span is being dynamically created by PHP. However, I am uncertain how to efficiently target the text string in order to begin using jQuery. <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Se ...

At times, the map may only be visible in the top left corner of its designated container

Currently, I am integrating the Google Maps API v3 for JavaScript into my project. However, I am facing an issue where the map only appears in the upper left corner under certain circumstances. To visualize this problem, you can visit this link and click ...

Fixing Broken JSON in Java: A guide to repairing malformed JSON

Using Java and Regex, I am parsing a config file and obtaining an ArrayList of strings in a specific format. To convert the example above into valid JSON, here is what I need: { "ssid": "test1", "psk": "154695", "key_mgmt": "WPA-PSK", "si ...

Looking for assistance with converting a basic script into a Joomla 2.5 module and resolving issues with Java integration

I'm having issues with my code in Joomla 2.5. It seems like the Java function is not functioning properly within Joomla. Can someone assist me with troubleshooting this problem? mod_mw_pop_social_traffic.php <?php defined( '_JEXEC' ) or ...

What is the best way to programmatically choose an option from a ng-select dropdown list?

My program displays a list to the user utilizing ng-select. This particular list is populated with various items: item 1 item 2 item N The user has two options when interacting with this list. They can either select an existing item or add a new one. If ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...

react-vimeo not firing onPause and onPlay events

I am facing an issue with triggering props when playing a Vimeo video on my webpage. Here's a snippet of my code: import Vimeo from '@u-wave/react-vimeo'; const handleVimeoProgress = (data: any) => { console.log('Progress:' ...

WordPress header causing issues with Document.write()

I have a JavaScript function that utilizes AJAX to retrieve data from a PHP file. Previously, I utilized document.write(data) to display the retrieved content and it worked smoothly on its own. However, upon incorporating the script into WordPress via hea ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Troubleshooting problems with form submission through the combination of jQuery and Ajax

Hi there! I've got a couple of questions regarding form submission using jQuery and Ajax. Currently, I'm working on validating a login form using jQuery/Ajax requests. My goal is to disable the login submit button after a successful login. Howev ...

Storing customer information securely on the server with the help of Node.js

After spending some time experimenting with Node.js on my local machine, I've realized that my understanding of HTTP requests and XHR objects is quite limited. One particular challenge I've encountered while using Node is figuring out how to effe ...

React throwing an error when attempting to include a Link component from react-router-dom

Currently working on a React app and encountering an issue while trying to add the Link component from the react-router-dom package. The main routes are defined in the App.js file structured as follows: https://i.stack.imgur.com/BF8M8.png The <Header ...

Changing the dataURL of jqGrid dynamically after loading the Edit Form

Currently, I am working with jqGrid version 4.15.6-pre, which is the free version of jqGrid. Within my edit form, I have two dropdown lists that are being populated from the server using setColProp in the onSelectRow function. My objective is to reload t ...

Errors encountered by the Chrome extension

Hey there, I've recently delved into creating a chrome extension but hit a roadblock. My issue revolves around the service worker registration failing and encountering errors related to undefined properties. https://i.stack.imgur.com/bGzB4.png The c ...

Prevent entry into property in Ionic 2 course

I receive a dynamic translation file from a server periodically, and I'm unable to modify its format. When a new page is instantiated in my Ionic App, I assign the value from storage to this.translations. See the constructor below: constructor(stora ...

What could be causing my project to install an erroneous Angular version?

It appears that my project is not utilizing the latest Angular code, but I am unsure of the reason behind this. I have checked my package.json file and found the following dependencies: "devDependencies": { "@angular/common": "2.0.0", "@angular ...