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

In JAX-RS, the attributes of a POJO are being returned as an Array in JSON format

Running a java web maven project with JAX-RS using resteasy version 2.2.1.GA implementation. All JAX-RS resources on the project produce and consume application/json. The issue arises when trying to return a single POJO or an array of it, as only the value ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...

Create a roster of numbers that are multiples using a systematic approach

Is the following code a functional way to return multiples of 5? function Mul(start,array,Arr) { Arr[start]=array[start]*5; if(start>array.length-2){ return Arr; } return Mul(start+1,array,Arr); } var numbers =[1,2,3,4,5,6 ...

What is the best way to transmit a response from PHP to Ajax?

A JavaScript function is used here that utilizes the POST method to send form data to PHP. The PHP script then checks this data in a database to verify its authenticity. However, there seems to be confusion on how to convey the response from PHP back to Ja ...

What is the process of transforming JsonForm into Json format?

Looking to extract specific data from a JSON file and convert it into a JsonForm using Java. Can anyone recommend a suitable framework for this task? ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

What is causing the search filter in the App.js code to malfunction?

After fetching a list of names from an array using the Fetch method, I attempted to implement a search filter by adding the resetData() method in my componentDidMount. Unfortunately, this resulted in an error as shown here: https://i.stack.imgur.com/1Z7kx. ...

Delay in displaying Promise API call in NextJS

Currently, I am encountering an issue while making calls to an API function that I have already set up and confirmed to work flawlessly in other projects. Interestingly, I have utilized the same backend API calling method in another project as well as with ...

Retrieve the selected checkboxes from the latest .change() trigger

I'm facing an issue with a basic question that I can't seem to find the right terms to research for help. The problem revolves around a .change() listener that monitors checkbox changes within a div (used to toggle Leaflet Map layers). My goal i ...

Exploring the Power of JQuery AJAX Requests and Analyzing Google Trends

Currently, as a first-year Computer Science university student, I have taken on the task of creating a website that utilizes Google Trends data. My goal is to use only jQuery / JavaScript for this project. I am attempting to retrieve the JSON data provide ...

The Meteor update is unsuccessful on the Mongo Sub Collection and will not continue

I am currently facing an issue with updating a specific object within an array in my object based on a value. Whenever I try to add the update code, the function gets stuck at that point without proceeding further. None of the console.log calls after the u ...

Interacting between host and remote in microfrontend communication

In my microfrontend application utilizing module federation, I am facing the challenge of establishing communication between the shell and remote components. When the remote component communicates with the shell using CustomEvent, everything works smooth ...

The video.play() function encountered an unhandled rejection with a (notallowederror) on IOS

Using peer.js to stream video on a React app addVideoStream(videoElement: HTMLVideoElement, stream: MediaStream) { videoElement.srcObject = stream videoElement?.addEventListener('loadedmetadata', () => { videoElement.play() ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

Employ ion-grid for a layout reminiscent of Duolingo's design

I am exploring the idea of creating a layout similar to Duolingo's interface. I have an array that specifies which buttons should be displayed, and I want them to be organized in pairs, with any odd element centered within the layout. However, I am s ...

Tips for utilizing withNavigation from react-navigation in a TypeScript environment

Currently, I am working on building an app using react-native, react-navigation, and typescript. The app consists of only two screens - HomeScreen and ConfigScreen, along with one component named GoToConfigButton. Here is the code for both screens: HomeSc ...

Preparing data in the Vuex Store efficiently for an AJAX request

Dealing with a Vuex store that holds around 30 fields has been quite the challenge for me over the past couple of days. I've been struggling to properly gather the data before sending it through an AJAX post method. Being aware of the reactivity of Vu ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

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 ...