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

Display JSON information in a grid using JQuery

I'm on the lookout for a simple json grid plugin to make my life easier. I need to populate a grid using JSON/Ajax, but the catch is that the amount of data or columns will vary each time, so it needs to be able to adapt accordingly. For example, a p ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

How come a Google Maps API component functions properly even without using *NgIf, but fails to work when excluded in Angular 9?

I recently followed the guide provided in this discussion with success. The method outlined worked perfectly for loading search boxes using this component: map.component.html <input id= 'box2' *ngIf="boxReady" class="controls" type="text" p ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

The role of the colon in extracting data from an AJAX request

Curiosity arises around the usage of the colon, :, in data. It is clear that the data is sent to list.php, but the exact process remains unclear. function paint(val){ $(".loading").css("display","block"); $.ajax({ type:"POST", ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

PHP Array Element Output

After making a call to the Twitter API, I have received an Array of data containing the "Top 10 Trending" items. However, I am facing difficulty in printing out the individual elements such as names. Below is the code snippet that I have been using to disp ...

Instructions for serializing a Jackson field as a JSON string rather than an object

Working with Amazon SNS push notifications involves sending a specific payload format: { "default": "This is the default message required when publishing a message to a topic. It will be used if no message is specified for a platform.&quo ...

Guide on converting a JSON object into a TypeScript Object

I'm currently having issues converting my JSON Object into a TypeScript class with matching attributes. Can someone help me identify what I'm doing wrong? Employee Class export class Employee{ firstname: string; lastname: string; bi ...

Issue arose following the update from Angular 5 to 6, impacting the VSTS build process

Upon upgrading from Angular 5 to 6, I successfully got it running locally. It builds and compiles with --prod. Integration into an .NET MVC application went smoothly. However, when the build on VSTS is triggered, a series of errors surface: node_modules&b ...

Can the while loop combine all rows into a single row?

I am facing an issue where my loop is only returning one row of data when I try to fetch all rows from a table with a foreign key. The returned row contains scattered data from multiple rows instead of the complete set. $query = 'SELECT * FROM car_re ...

In the presence of objects, the JSON parser experiences a crash

After receiving a JSON reader based on an inputStream, I encountered an issue with parsing objects. While parsing strings or integers works fine, parsing an object (such as the one with attributes firstName and lastName) poses a problem. Here is how the JS ...

iOS Development: Extracting dictionaries with numerical keys using JSONModel

Currently, I am utilizing JSONModel developed by icanzilb for parsing my online obtained JSON structures. The challenge lies in the fact that I have a dictionary with numerical keys, and these keys are dynamically generated by the server as needed. Therefo ...

Authorization setup encountered an issue: an unexpected character was found at the beginning of the JSON data on line 1, column

I'm currently in the process of setting up a login page for users on my website, using mongoose, express, bcrypt, and nodejs. However, I am encountering an issue when trying to input the username and password. The error message that I receive is as fo ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

Python is unable to correctly query JSON LOAD due to a syntax error

I'm encountering an issue while attempting to retrieve data from the sig API. Despite providing the correct URL, an error is being generated. import requests import json from json import loads import pandas as pd import matplotlib as plt requests.ge ...

What is the correct way to import scss files in a Next.js project?

Currently, I am working on a NextJS project that uses Sass with TypeScript. Everything is running smoothly in the development environment, but as soon as I attempt to create a build version of the project, I encounter this error. https://i.stack.imgur.com ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

What is the correct way to define types for higher-order class components in TypeScript?

I have developed a utility function that currently has an unused options parameter, and it returns a higher-order component wrapping function. How can I effectively define types on the component so that users of the wrapped component can visualize the typ ...