Changing a JSON string into JSON arrays within Angular 6

Hello, I am looking to convert the RestController Response from a Json String to a json array. Below is the json string that I have printed in the console:

'{"Impressions":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Clicks":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Revenue":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"]}'

My goal is to convert it into a json array so that I can iterate over it.

The purpose of this iteration is to use the key as a label and the corresponding values as select options.

For example:

"Impression" would be the label with options "Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate".

Here is the code snippet for iterating through the array:

<div>
   <form *ngFor ="let map of mapper">
      <mat-form-field>
         <mat-select placeholder="{{map}}">
            <mat-option *ngFor="let option of map"  [value]="option"> 
                {{option}}
             </mat-option>
         </mat-select>
      </mat-form-field>
    </form>
</div>

And here is my .ts class code:

this.clientService.getHeaders().subscribe(
      (res) => {
          console.log(res);
          let resSTR = JSON.stringify(res);
          let resJSON = JSON.parse(resSTR);
          this.mapper=Array.of(resJSON._body);

          console.log(this.mapper);
          this.ismapped=false;
}
);

Answer №1

this.clientService.getHeaders().subscribe(
  (response) => {
      console.log(response);
      let data= <any>response;
      this.mapper= data;
      console.log(this.mapper);
      this.isMapped=false;
  }
);

There's no need to convert the response to a string and then parse it. Simply cast the response to any type and you'll be able to use it as an array.

Answer №2

let data = '{"Impressions":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Clicks":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Revenue":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"]}'

Object.keys(JSON.parse(data)).map(item => {
  return `${item}: ${JSON.parse(data)[item].join(', ')}`;
});

You can customize the return statement as per your requirement. It could be a string, an array, or even an object.

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

Customizing the background color in TurnJSIncorporating

Recently, I encountered a problem that has left me puzzled. Despite searching online for help, I have not been able to find a solution. The issue lies with the basic code provided on the official page of the TurnJS script. <div id="flipbook"> <di ...

Tips for effectively integrating NG-TEMPLATE, NG-FOR, and NG-IF with a child component

Let me share a scenario... // child-component.ts @Input() attrOne: any; @Input() attrTwo: any; isVisible: boolean = true; HideThis(){ this.isVisible = false; } Additionally... // child-component.html <div *ngIf="isVisible"> <!-- content in ...

An error has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out ho ...

Encountering a clash with AJAX while attempting to incorporate PayPal

I am currently facing an issue while trying to integrate PayPal payment into my website. The problem arises when I attempt to use Ajax to send shopping cart data to create an order, resulting in the following alert message: Failed to load Response to pref ...

A text box lacking the right side scrollbar

Can CSS be utilized to eliminate the right side scrollbar on a <textarea> element? ...

The JSONDecoder encountered issues while trying to decode nested dictionaries

I've encountered an issue while using JSONDecoder to decode a JSON file containing nested dictionaries. The decoding process fails to map the JSON data into my customized model. This is the code snippet I've attempted: The JSONDecoder implemen ...

Backbone causes a sudden influx of unexpected AJAX requests

I included the fetch URL with a deferred method, expecting it to only make one remote AJAX request. However, I noticed that it is being called three times when the page loads. Does anyone know how to resolve this issue? Thank you JS Scripts var Commen ...

How can I confirm that all elements have been properly reset to their original positions prior to making any further adjustments to them?

In need of some creative brainstorming, I'm working on a website design featuring ten overlapping cards. When the mouse hovers over a card, it expands while others move away. My goal is for each card to return to its original position once the cursor ...

Passing data as a parameter from the view to the controller using AngularJS

I am attempting to retrieve data from a view, which must be passed as a parameter in a function in order to populate an array in the controller. However, I am not receiving any objects in return. Here is what I have tried: VIEW <div ng-repeat="cssfram ...

Which tools offer methods for converting JSON into objects of model classes?

When it comes to finding tools that can transform JSON into specific model classes for different programming languages such as C#, Objective-C, and Java, the options are plentiful. However, what if I want to customize this transformation process and crea ...

The issue arises when HTML tables with unique IDs are all displaying the same value from an AJAX callback

This situation has been incredibly frustrating for me!! Let me explain what's going on - I have a callback data coming from my AJAX post method that needs to be passed to seven different HTML tables. Although I successfully received the data from the ...

My goal is to eliminate any characters that are not numbers and any punctuation marks except for the period

I am looking to eliminate all non-numeric symbols and punctuations except for periods ".". I have managed to remove all non-numeric symbols using the following code: if (!/^[0-9]+$/.test(this.value)) { this.value = this.value.replace(/\D/, ""); ...

What is the process of emphasizing a WebElement in WebdriverIO?

Is there a way to highlight web elements that need to be interacted with or asserted in webdriverIO? Or is there a JavaScript code similar to the javascript executor in Selenium that can be used for this purpose? ...

Overcome the issue of 'Parsing Error: Kindly verify your selector. (line XX)' in Javascript/AWQL

Hello there! Just to clarify, I am not a developer and my coding skills are limited to basic HTML. Your patience is greatly appreciated ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

Unable to generate a proper JSON reply for the client

When making a request, I typically use the following method: $.ajax({ url: myUrl, type:"GET", dataType: "json", success: callback }); After forming a JSON string on the server side, I send it to the client which looks like this: ...

Encountered an issue while attempting to send a POST request using AngularJS $

I am facing an issue with accessing the POST method from my server. Whenever I log the response, it always returns status=0. Can anyone help me out or provide some advice? Note: I have tested the method in Postman and it works fine. Below is the code snip ...

Troubleshooting problem with hiding options in Jquery Chosen

Utilizing the chosen multiple selection feature, I have encountered an issue where selected options remain visible after being hidden and updated. Here is the code snippet: $("#ddlcodes").find("option[value ='" + codeValue + "']").hide(); $("#d ...

Angular making sequential api calls

I have the following code where I am making one API call after another, with the second API call nested inside a subscribe. Is it possible to use mergeMap in this scenario to avoid multiple subscribe calls? Here is my current code: saveEmployees(empObje ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...