Exploring a JSON Object in TypeScript: A Step-by-Step Guide

I am currently utilizing Angular 7 and have a query that returns JSON data with a specific format:

[
    {
        "text": "test 1",
        "value": "1",
        "nbr": "1",
        "children": [
            {
                "text": "test 1_1",
                "value": "1_1",
                "nbr": "2",
                "children": [
                    {
                        "text": "test 1_1_1",
                        "value": "1_1_1",
                        "nbr": "1",
                        "children": []
                    },
                    {
                        "text": "test 1_1_2"",
                        "value": "1_1_2",
                        "nbr": "0",
                        "children": []
                    },
                    {
                        "text": "test 1_1_3"",
                        "value": "1_1_3",
                        "nbr": "0",
                        "children": []
                    }
                ]
            },
            {
                "text": "test 1_2",
                "value": "1_2",
                "nbr": "0",
                "children": []
            }
        ]
    },
    {
        "text": "test 2",
        "value": "2",
        "nbr": "0",
        "children": []
    }
]

My goal is to iterate through this data and specifically loop through the children data.

Additionally, I need to perform some tests along the way.

Here is the code snippet I've tried so far, but I'm facing an issue looping through the children data:

      this.httpservice.query({

      }).subscribe((res: HttpResponse<TestEntity[]>) => {
        this.temp= res.body;

        this.temp.forEach((x) => {


            x["children"].forEach(x => {
                if(x.nbr=='0')
                {
                  //  test code
                }
                x["children"].forEach(x => {
                    if(x.nbr=='0')
                    {
                        //  test code
                    }

                    })
                })



            });


      });

I'm struggling to find a way to efficiently loop through the children data in this scenario.

Any assistance or guidance would be highly appreciated.

Answer №1

We could potentially try:

let objectArray = Object.keys(data).map(key => data[key]);

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

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

ContentChildren to gather all offspring

Currently, I am in the process of compiling a list of components using data from the Back End. I have implemented a ContentChild object to obtain their reference, however, it seems to be empty. I also attempted using ViewChild, but it only captures the fir ...

Displaying subsets of data based on the identifier of the primary array

In my JSON file, I have an array containing various categories and their respective subcategories. { "Women": [ { "id" : 1, "name" : "See All", &q ...

How to Override Global CSS in a Freshly Created Angular Component

My CSS skills are a bit rusty and I need some assistance with a project I'm working on. The project includes multiple global CSS files that have properties defined for different tags, such as .btn. However, these global CSS files are causing conflicts ...

Is there a way to integrate TypeScript into the CDN version of Vue?

For specific areas of my project, I am utilizing the Vue CDN. I would like to incorporate Typescript support for these sections as well. However, our technical stack limitations prevent us from using Vue CLI. Is there a method to import Vue.js into a bas ...

Implementing Class-based Dependency Injection in Express

Incorporating Express into a TypeScript project has presented me with a particular scenario Here is my route file: ... import findAllUsersFactory from "src/factory/FindAllUsers"; routes.get("/users", findAllUsersFactory().handle); ... ...

How can I extract a specific data value from a JSON file in Ionic 2?

Here is the JSON data: [ { "id": 1, "label": "saw", "total": "100" }, { "id": 2, "label": "saw1", "total": "300" }, { "id": 3, "label": "saw2", "total": "400" } ] Below is my Typescript code snippet: this. ...

Is it possible to retrieve a value obtained through Request.Form?

Within my Frontend, I am passing an Object with a PersonId and a FormData object. const formData = new FormData(); for (let file of files){ formData.append(file.name, file,); } formData.append('currentId',this.UserId.toString()); const upl ...

How can I invoke TypeScript methods within a jQuery event handler in the ngAfterViewInit lifecycle hook?

I am currently utilizing Angular 4. I need to invoke methods from a typescript file within the ngAfterViewInit method. declare var $; @Component({ selector: 'app-details', templateUrl: './details.component.html', styleUrls: [&apo ...

Typescript's Type Specification

I am currently working with NextJs and Typescript and I am facing an issue. Whenever I include the "any" keyword in my code, it renders correctly. However, if I remove it, I encounter errors with post._id, post.title, and post.body. Challenge: Can someon ...

The error persists in Ajax requests despite the correct usage of json_encode and everything functioning correctly

In the realm of e-commerce, I have successfully implemented an AJAX request to dynamically add and remove items from the cart. Interestingly enough, every time the jQuery script is executed, everything seems to be working seamlessly. The server always resp ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

How can we avoid a runtime error when attempting to filter an array that may not be present at a certain point in

Encountering a runtime error with my reducer state chunk - specifically a TypeError stating that an intermediate value is not iterable. This occurs when the object, childGroup, may not be present in the state at a given moment. Any solutions on how to avoi ...

My webpage is experiencing issues with function calls not functioning as expected

I have created a select menu that is integrated with the Google Font API. To demonstrate how it works, I have set up a working version on JSBIN which you can view here. However, when I tried to replicate the code in an HTML page, I encountered some issues ...

How can I use regex within a pipe to split a string in Angular 4?

I need to implement a method where I can split a string based on special characters and spaces in the given regex format, excluding "_". Example: #abc_xyz defgh // output #abc_xyz Example: #abc@xyz defgh // output #abc Example: #abc%xyz&defgh // out ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

The JSON Post Request functionality is encountering issues within ASP.NET5 MVC, whereas it is functioning properly in ASP.NET4.5 MVC

I am encountering an issue with a JSON post request to an MVC controller. It works fine in ASP.NET 4.5 but fails in the latest ASP.NET 5 release. Am I overlooking something in my setup? I have created a model, but I haven't bound it to a database. ...

Utilizing a Map with Angular's ngFor

Currently, I am working with Ionic 3, which utilizes Angular and TypeScript. My goal is to use ngFor with a Map type in my project. Below is what I have implemented so far: interface IShared_Position { lat: number; lng: number; time: number; ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...

Using Typescript to deliver the parent component's props to its children prop

I have a goal to create a versatile component that can accept different props based on its usage in the project. The component should output its children prop along with all the given props (flow-through) and potentially some new constants calculated based ...