Loop through a JSON object in TypeScript and extract each element from the JSON

I am still learning TypeScript and trying to accomplish a rather simple task, however the documentation does not provide guidance on how to iterate over JSON data. My goal is to loop through a JSON response array and insert a JSON object into each element. Here is the code I have been working on, but the TypeScript evaluator in WebStorm is flagging an error stating that speakerElement is a string and not a JSON object, making it impossible to use the put function.

return new Promise(resolve => {
   this.http.get('http://.staging.wpengine.com/wp-json/wp/v2/cr3ativspeaker')
   .map(res => res.json())
.subscribe(data => {
  console.log("the speaker data is : ", data);
  console.log("the speaker data is : ", JSON.stringify(data));
  //get each speakers image and append it to their data
  for(let speakerElement in <JSON>data) {

    this.http.get('http://.staging.wpengine.com/wp-json/wp/v2/cr3ativspeaker')
      .map(res => res.json())
      .subscribe(response => {

       speakerElement.put("media_details", response.media_details);

      });

  }

  this.data = data;
  resolve(this.data);
});
});

Answer №1

Firstly, I want to express my gratitude for the helpful suggestion. I managed to find the solution by making a slight adjustment. Instead of using in in my For Loop, I needed to use of. The revised code is as follows:

 for(let speakerElement of data) {
            console.log("Speaker element",speakerElement);// element is JSON 

          }

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

Displaying a React component within a StencilJS component and connecting the slot to props.children

Is there a way to embed an existing React component into a StencilJS component without the need for multiple wrapper elements and manual element manipulation? I have managed to make it work by using ReactDom.render inside the StencilJS componentDidRender ...

A guide on decoding a JSON string sent via POST request and parsing it into variables using PHP

How can I process JSON data that is sent to my URL and extract the values into variables? { "ccToken": "75676576765", "cardType": "CC", } I am new to this and unsure of how to handle a JSON string being posted to my URL. Typically, I can accept variab ...

Transforming a deeply nested list of dictionaries into a Pandas Dataframe

I've been analyzing the following JSON structure {"response": {"GDUEACWF": {"2018-06-01": [{"groupwide_market":"Developed Markets", "weights":0.8794132316432903}, {"groupwide_market":"Developed Markets ...

Ensure that all files with the extension ".ts" take precedence and are imported

I am facing an issue with my component as I have two files associated with it: app/components/SomeButton.ts app/components/SomeButton.tsx The .ts file contains most of the logic and code, while the .tsx file extends the .ts and only contains the ren ...

Statically Define JSON Array in PHP

I am facing a challenge where I need to combine two variables from separate SQL queries into one JSON Array. The variables are $hometown and $topcat, and although I have attempted to hardcode it, I am unsure of the correct format. print(json_encode(' ...

Use Angular's super.ngOnDestroy method for handling cleanup/unsubscribing

When it comes to unsubscribing / cleaning up from observables in Angular components (using ngOnDestroy), there are multiple options available. Which option should be considered the most preferable and why? Also, is it a good practice to include super.ngOnD ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Is there a method to trigger the opening of a calendar downwards within a modal?

I am having an issue with a p-dialog that contains a p-calendar. The problem is that when I try to open the calendar, it pops up upwards instead of downwards. <p-dialog responsive="true" modal="true" (onHide)="closeDialog()" #genericDialog [(visi ...

Invalid JSON due to escaped HTML characters

After using a tool to escape all characters in my JSON containing HTML code, I encountered an issue when trying to validate it. The error message received was: Parse error on line 2: { "html": "<table class=\"MsoT -----------^ Expecting &apos ...

class with an expanded base interface incorporated

I am struggling with the implementation of an extended interface in a class. Below is a simplified example (with playground link at the end of the post): interface A { hello:string } interface Extension extends A { bye:string } class Greeting im ...

Generating JSON data on an iPhone using integers and booleans

When using the json-framework for iPhone from http://code.google.com/p/json-framework/, it's a breeze to generate JSON data from an NSDictionary. Here's how: NSString *json_string = [json_parser stringWithObject:dictionary]; While this method w ...

Parsing the ScalaJSON Reads[T] function resulted in a ValidationError with the error message "error.path.missing" and

My JSON data is structured like this: [ { "internal_network" : [ { "address" : [ { "address_id" : 2, "address" : "172.16.20.1/24" }, { "address_id" : 1, "address" : "172.16.30.30/24" } ] } ], "switch_id" : "000000 ...

Testing an event within a subscription in Angular 4: A step-by-step guide

I am facing an issue with my component where I subscribe to an event in the constructor. To send an event, I use an event service: import {Injectable} from '@angular/core'; import {Observable} from "rxjs/Observable"; import {Subject} from "rxjs ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...

Having issues configuring CustomJacksonMapper to handle DateTime in Spring 4.1.5

Below are the configurations I've implemented: Configuration in my config file: <mvc:annotation-driven> <mvc:message-converters> <!-- Support for Joda Time --> <bean class="org.springframework.http.converter ...

Instructions on how to extract and display the key-value pairs from a nested JSON array in Angular 2, then populate them in a select box

My goal is to extract data from a Json data model and populate a select box with the data as drop-down items. However, I am encountering difficulties in achieving this as the entire Json array is being printed instead of just the 3 major headings that I wa ...

Importing from source code instead of a file in TypeScript: How to do it

I found this code snippet to help with dynamic component loading: loadComponent(name) { var url = this.configurationService.configuration.api_url+"/generator/dynamic-loading/component/"+name; this.http.get(url, {responseType: 'text'}). ...

Struggling with defining content and background scripts while using AngularJS2 CLI to build a Chrome extension

After creating a brand new AngularJS-2 application using the cli tool from github, I discovered that running ng build compiles my sources into a /dist folder. As I am developing a chrome extension, I need to specify the location of my content script (whi ...

How to set focus on an input element in Angular 2/5

After clicking, the input element is displayed (it is initially hidden). I want this input to be in focus when it appears. This functionality works well when the input is not hidden by *ngIf (#inputElement2). Is there a way to achieve the same for #inputE ...

Is There a Comparable Feature to *ngIf in DevExtreme?

Currently, I am diving into the world of webapp development using DevExtreme. As a novice in coding, this is my first time exploring the functionalities of DevExtreme. Essentially, I am seeking guidance on how to display certain elements based on specific ...