Retrieving data from a JSON using Typescript and Angular 2

Here is an example of what my JSON data structure looks like:

{
  "reportSections": [
    {
      "name": "...",
      "display": true,
      "nav": false,
      "reportGroups": {
        "reports": [
          {
            "name": "...",
            "url": "reportLibrary.tableau",
            "nav": true,
            "params": {
              "reportName": "clientRelationshipReport",
              "reportTitle": "Client Relationship Report",
              "reportUrl": "...",
              "reportHeight": "4030px"
            },
            "filters": "clientName,brokerName,entity,budgetClass,practice,office"
          }
        ]
      }
    }
  ]
}

Within the HTML file template in the component, I have the following code:

<li *ngFor = "let sectionName of reportNavJSONMain.reportSections">
     <span> {{ sectionName.name }} </span>
     <ul>
       <li *ngFor="let report of sectionName.reportGroups.reports">
          <a *ngIf="report.nav"> {{report.name}} </a>
       </li>
      </ul>
 </li>

Below is a snippet of how the component method in component.ts appears:

//<irrelevant code> 
....
getReports(): any {
    new Promise((resolve,reject)=>{
      resolve(
        this.reportNavService.getJSONReportMain()
      )
    }).then((data)=>{
      // console.dir(JSON.parse(JSON.stringify(data)));
      this.reportNavJSONMain = JSON.stringify(data);
      console.dir(this.reportNavJSONMain)
    })
  }
  ...
  //<irrelevant code>

The service code used to retrieve the JSON data is as follows:

//.... 
public getJSONReportMain(): Promise<any> {
    return this.http.get('...')
      .toPromise()
      .then((response: Response)=>{
        //console.log(JSON.stringify(response.json()))
        this.reportNavJSON = JSON.stringify(response.json());
        return this.reportNavJSON;
      }).catch((error: Response)=>{
        return Observable.throw('Error');
      });
  }
  // ....

In the component.ts file, despite initializing this.reportNavJSONMain as an object (or array), it always displays as an "Object" when logged with console.log() or console.dir(). Various methods like JSON.parse() and JSON.stringify() were attempted but did not solve the issue.

The main objective is to access reportSections from this.reportNavJSONMain, however, attempting

this.reportNavJSONMain.reportSections
does not indicate that reportSections exists within this.reportNavJSONMain. Yet, both
console.dir(this.reportNavJSONMain)
and
console.log(this.reportNavJSONMain)
display the nested data structure properly.

Answer №1

String navigation/iteration is not possible, but object navigation/iteration is!

(Assuming that this.reportNavJSONMain was declared as either a var or Object)

If the data is an Object

).then((data)=>{
    this.reportNavJSONMain = data;
})

If the data is a String

).then((data)=>{
    this.reportNavJSONMain = JSON.parse(data);
})


Here's an example of how you can implement this in JavaScript,

var object = {
  "reportSections": [
    {
      "name": "...",
      "display": true,
      "nav": false,
      "reportGroups": {
        "reports": [
          {
            "name": "...",
            "url": "reportLibrary.tableau",
            "nav": true,
            "params": {
              "reportName": "clientRelationshipReport",
              "reportTitle": "Client Relationship Report",
              "reportUrl": "...",
              "reportHeight": "4030px"
            },
            "filters": "clientName,brokerName,entity,budgetClass,practice,office"
          }
        ]
      }
    }
  ]
}

var p = new Promise((resolve, reject) => {
  resolve(object);
});

p.then((data) => {
  data.reportSections.forEach((section) => {
    console.log(section.reportGroups);
  })
});

Answer №2

Instead of converting your JSON result into a string using JSON.stringify(), ensure to use result.json() in your service on the http result directly. This will immediately provide you with the result in JSON format.

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

Recovering antiquated submission script in JavaScript

Here is a form with input data: <form id = 'myform'> ... <td><input type="checkbox" name="supplier_aid" value="on" checked disabled >{$output.t_artikelnr}</td> <td><input type="checkbox" n ...

What is a regex with a touch of greed in its capture

I am considering the following options: ' !This is a string! ' '!This is a string !' '! This is a string !' ' ! This is a string! ' ' ! This is a string ' For each of these scenarios, I aim to find ...

not capable of outputting findings in a sequential manner

I am encountering an issue where my result is not printing line by line, instead everything shows up on a single line. How can I resolve this problem? Here is the code snippet I have tried: <script> function know(){ var num = Number(doc ...

Issue encountered when trying to pass a string into URLSearchParams

const sortString = req.query.sort as string const params = Object.fromEntries(new URLSearchParams(sortString)) Upon moving to the implementation phase, I encountered: declare var URLSearchParams: { prototype: URLSearchParams; new(init?: string[][] ...

Bypass the Array.reduce method in JavaScript

I'm currently working on finding an elegant solution to a toy example pattern. The goal is to stop the reduce algorithm immediately and return 0 when an element with a value of 0 is encountered, without processing the rest of the elements. let factor ...

Create a nested struct definition in Golang and ensure it contains identical objects

Here is a struct that I am working with: type AutoGenerated struct { Accounting []struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` Age int `json:"age"` } `json:"accounting"` Sales []struct { FirstName string ...

utilizing vue model attributes with `${}`

I am encountering an issue with my code. Initially, :src="labels[index]" was working fine for me. However, as my codebase expanded, I needed to use ${app.labels[index]}. Simply using ${app.labels} works, but the addition of [index] causes it to b ...

Getting the value of a hidden input field within a div by accessing the event.target that initiated the event in JavaScript

I am working with a set of li elements, each containing specific child elements structured like this: <li class="list"> <!--Parent--> <input type="hidden" id="id" value="3"> <!--Child 1--> <div class="cd-1">....</div ...

hitting the value of the text input

Is there a way to strike through only the first word in an input box of type text, without editing the html? I've tried using css text-decoration: line-through; but it's striking both words. Any suggestions on how to achieve this using javascript ...

Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function? const func = (x:number, ...

Tips on sending a jsonp request in Angular2 without relying on JSONP_CALLBACK

I am attempting to send a JSONP request to a third-party website, where the callback name remains constant, regardless of what I input in the callback= parameter. Is there a method in Angular2 to specify a custom callback name? ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

During the build process, NextJS encountered an issue locating the constants.js module

I encountered an error while executing next build using next version ^10.2.3. I attempted to remove the node_modules and .next folders, then reinstalled dependencies with npm install && next build, but the issue persists. Error: Cannot find mod ...

What is the reason behind combining all states into a single location in Redux, even if they are not globally accessible?

As a newcomer to React and Redux, I have found them to be quite enjoyable when used together in a small sandbox application. However, as I consider larger applications, I can't help but question why Redux stores the entire application state in a singl ...

Extract HTML content using CKEditor

Hey there! I'm in need of some help with getting user-entered data from a textarea. I've already attempted using CKEDITOR.instances.editor1.getData() and CKEDITOR.instances.ckeditor.document.getBody.getHtml(), but unfortunately both only return ...

Iterate over each key in a JSON object to verify if its corresponding value is blank

I am dealing with a JSON object that has empty values for the keys remarks and address. When extracting the JSON, it displays undefined for these empty values. However, I want to replace the empty values with a - sign instead. I understand that I can achie ...

Is it possible to retrieve values from my model when working with Django Templates and incorporating them in the JavaScript header?

With Django, I have managed to successfully retrieve and display data from my model in the content section of the template. However, I am facing issues retrieving data from the model in the header section of the template. Below is the code --> view.py ...

Creating a custom event for every reference within a Vuejs for loop

I'm working with a loop of data and have a modal for each iteration <div ref="vuemodal-{{loop.index}}"> Each modal is a bootstrap modal, and I want to bind an event to them that triggers whenever the modal is closed mounted(){ Obj ...

Accessing values in a JSON object using C#

How do I extract a value from a JSON Object? Should I convert it into a class or can I retrieve it directly from the .json text file? Here is an example of the JSON file I have created: { "801": { "Name": "Tarlac", & ...

Apply a specific style conditionally using Angular's ng-repeat directive

Currently, I am utilizing ng-repeat to iterate through a list of divs and manually adding items to the JSON that is rendering these divs. My goal is to position the last div that I add in the JSON at the location where the mouse cursor is, while keeping th ...