Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this:

{
   "status": "success",
   "code": 0,
   "message": "version list",
   "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta\",\"country\":\"CA\"},{\"code\":\"BC\",\"short\":\"BC\",\"name\":\"British Columbia\",\"country\":\"CA\"}]"

}

I am facing a challenge where I need to extract the names of different objects from the payload. The issue is that the payload is returned as a string.

Despite my efforts to retrieve the object names, I have not been successful so far!

getAllPayload() {
  this.myService.getpayload().subscribe(
     data => {
        this.values= data;
     }
   );
}     

Additionally,

<select class="form-control">                     
   <option *ngFor="let value of values.payload" >
      {{value.name}}
   </option>
</select>

Even attempting to parse the object using JSON.parse has been unsuccessful.

I'm stuck! Can anyone guide me on how to properly parse the payload and fetch the different names?

Answer №1

Your String contains unescaped quotes which need to be fixed first.

Use JSON.parse() method

var result = {
"payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta\",\"country\":\"CA\"},{\"code\":\"BC\",\"short\":\"BC\",\"name\":\"British Columbia\",\"country\":\"CA\"}]"
};
  
var payloadData = JSON.parse(result.payload);
console.log( payloadData )
console.log( Array.isArray(payloadData) ) // true

Answer №2

To achieve your goal, you can follow this approach:

retrieveAllData() {
this.dataService.fetchData().subscribe(
    result => {
    this.items = JSON.parse(result.payload) // This code snippet is responsible for converting the payload string into an array.
    
    ;
  }
 );

After that, in your HTML template

<select *ngFor="let item of items" >
     {{item.name}}</option>
 </select>

This should provide you with a solution to your issue.

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

React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic. {MEMBERSHIPS.map((mItem, index) => ( <TableCell className="text-uppercase text-center" colSpan={2} padding="dense" ...

Placing a blank object after every line within a TypeScript array

I'm currently working on creating an iterator using the .map() function, specifically in this way: const csv = this.invoices .map(data => ({ invoiceId: data.invoiceId, invoiceDate: data.invoiceDate, invoiceType: data.invoiceType, ...

Ajax calls for validations are failing to trigger a response from PHP

I am currently working on validating my signup form using PHP and AJAX, but unfortunately, I am not receiving any response value. Below is the AJAX code snippet I am using: <script type="text/JavaScript"> function frmValidation(str) { ...

API Broker, transforming JSON into DataFrame

Recently, I encountered some challenges while trying to retrieve historical data from my broker's API (xTrade Brokers). Initially, I attempted the following code: import json import pandas as pd data=json.loads(history) dafr = pd.DataFrame(data,col ...

Encountering a hiccup while attempting to initialize a fresh Angular project with the command "ng new my

I encountered an error issue after running the command npm new project0 npm ERR! path D:\Polytech\Génie Informatique\2- Génie Informatique 4\Programmation Web\Angular\project0\node_modules\js-yaml\bin\js ...

Switching from Vanilla JS to Vue.js, dealing with querySelector problems

Seeking assistance with transforming the following CodePen example to a Vue.js component: https://codepen.io/kjbrum/pen/qooQJJ While attempting to incorporate this.$nextTick for handling DOM manipulation, I'm encountering challenges in making it func ...

Guide to importing an npm module with a Typescript main file in a Typescript project

I'm struggling to figure out the correct method for importing a Typescript npm module. Here is my current approach: module package.json { "name": "my-module", "main": "src/myModule.ts" } module src/myModule.ts export module MyModule { // Co ...

Encountering a JSONDecodeError when sending a python dictionary via AJAX post

I have encountered an issue when passing a Python dictionary to a template and then using $.post to send it to a Django view. When I attempt to json.loads it in the view, I am getting a JSONDecodeError. Does anyone know how I can resolve this? //1. vars t ...

"Run JavaScript code within the boundaries of the start and end of XMLHttpRequest

Currently, I am using XMLHttpRequest to execute an AJAX request without the use of jQuery, relying solely on plain old Javascript. This particular AJAX request may take some time as it calls an endpoint responsible for processing transactions. In order to ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

Guide on creating a JSON within a union function that results in an error

I encountered an issue while writing a union function that involved a json object as one of the parameters. The error message displayed was: could not identify an equality operator for type json. Below is the code snippet: select(SELECT array_to_json(array ...

Parsing JSON data in an Android application using HTTP response

My mobile app keeps crashing in the JSON parser class. I was following a tutorial and everything worked fine when it was connected to a MySQL database on localhost. However, now that I have hosted it on my HostGator account, I am encountering issues. Since ...

Guide for sending token through Authorization in Laravel 8 API

I am currently utilizing Laravel 8 as an API REST and encountering an issue where my token is null when sent in the AJAX request. I have successfully handled logins and requests without tokens, but this specific scenario has me puzzled. Within my JavaScri ...

Nested ControlGroup in Angular2's ControlArray

I've hit a roadblock trying to iterate through a ControlArray that has Controlgroups in a template. In TypeScript, I successfully created the ControlArray and added some ControlGroups by looping over data fetched from an API. The console displays the ...

Completing online form text entries in WebView without the need for identifying elements

I am currently working on a project to automate filling out an online login form using local string variables. This is the progress I have made so far: web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings() ...

What is the most efficient way to incorporate MongoDB into your codebase using ES6-style

I have encountered an issue with importing MongoDB using the es6 import-from style. When I try to import using node's require method, everything works fine. let mongo = require('mongodb'); let MongoClient = mongo.MongoClient; However, when ...

Learn how to instruct ajax to fetch the designated information and retrieve corresponding data from the database based on the selected criteria

Looking for some help with my 2 select boxes. The first box allows users to choose a brand, while the second box should display products from that brand fetched from the database. Unfortunately, I'm not familiar with AJAX and the script provided by a ...

Here's a method for transferring data from one array to another: when there is existing data in the

Although this may seem simple to some, I have been struggling with it for hours without any success. If I have the following data in an array: var tDataValues = { id: "TenantID", text: "FullName", username: "Username", cnic: 'CNIC&ap ...

Storing files offline in Firefox 3.5 with file:// protocol

While experimenting with the code for offline storage in Firefox 3.5, I referred to a tutorial on . When the page loads, I am prompted with a dialog asking to store data, but after clicking Allow, the dialog does not disappear. The application functions co ...

Using Vue.js to connect v-html to a custom CSS stylesheet

I am currently working with HTML generated by a function on an external server and I am able to preview this within a tag. Additionally, I can retrieve the CSS information in a similar manner. <template> <div v-html="html"></div ...