What is the best way to transform a singular array that consists of object strings into Angular 4?

productData(id){
    this.id=id;
    console.log("id"+this.id);
      let headers = new Headers();
    this.createAuthorizationHeader(headers);
return this.http.get(SharedServiceService.productDetails+this.id,{
        headers:headers
        })
      .subscribe(data => { 
          const products = data.json();
          this.productInfo=products;
          this.cart = this.storage.retrieve('cartList');
for(var i=0;i<this.cart.length;i++){
if(this.id==this.cart[i].id){
         this.addedOne=false;
        this.hideCart=true;
        this.continueShopping=false;   
}
}
          
var attr=[];
var storeLoc=[];
          attr.push(this.productInfo);
    console.log("attr",attr);
for(var i=0;i<attr[0].attributes.length;i++){
if((attr[0].attributes[i].name=='Next day store pickup') || (attr[0].attributes[i].name=='Store pickup')|| (attr[0].attributes[i].name=='Delivery price')|| (attr[0].attributes[i].name=='Shipping price')){
    this.prices.push(attr[0].attributes[i]);
        }
    console.log(this.prices);
}

for(var i=0;i<attr[0].attributes.length;i++){
if(attr[0].attributes[i].name=='Stores'){
for(var j=0;j<attr[0].attributes[i].options.length;j++){
    storeLoc.push(JSON.stringify(attr[0].attributes[i].options[j]));
}
}
}
           storeLoc.map((obj) => {
let data = obj.replace(/”/g, '"');
data = data.replace(/“/g, '"');
this.stores.push(JSON.parse(data));
})
              
          console.log("stores",(this.stores));
          console.log("id info"+JSON.stringify(this.productInfo));
        },
err => {
    console.log("Error!: ",err);
}
        );                              
}
storeLoc= [
                    "{“street”:”3104 Doctors Drive”,”city”:”Los Angeles”,”state code”:”CA”,”state”:”California”,”zip code”:”90017”}",
                    "{“street”:”3358 Cinnamon Lane”,”city”:”San Antonio”,”state code”:”TX”,”state”:”Texas”,”zip code”:”78212”}",
                    "{“street”:”573 May Street”,”city”:”Harold”,”state code”:”KY”,”state”:”Kentucky”,”zip code”:”41635”}",
                    "{“street”:”2836 Cantebury Drive”,”city”:”New York”,”state code”:”NY”,”state”:”New York”,”zip code”:”10013”}",
                    "{“street”:”2935 Kidd Avenue”,”city”:”St George”,”state code”:”AK”,”state”:”Alaska”,”zip code”:”99591”}",
                    "{“street”:”3676 Spirit Drive”,”city”:”Jacksonville”,”state code”:”FL”,”state”:”Florida”,”zip code”:”32220”}",
                    "{“street”:”2134 Shobe Lane”,”city”:”Moody”,”state code”:”AL”,”state”:”Alabama”,”zip code”:”35004”}",
                    "{“street”:”3614 Rhapsody Street”,”city”:”Aiea”,”state code”:”HI”,”state”:”Hawaii”,”zip code”:”96701”}",
                    "{“street”:”1756 Forest Drive”,”city”:”Ashburn”,”state code”:”VA”,”state”:”Virginia”,”zip code”:”22011”}",
                    "{“street”:”686 Upland Avenue”,”city”:”Toledo”,”state code”:”OH”,”state”:”Ohio”,”zip code”:”43609”}",
                    "{“street”:”574 Copperhead Road”,”city”:”Abercrombie”,”state code”:”ND”,”state”:”North Dakota”,”zip code”:”58001”}",
                    "{“street”:”3106 Tecumsah Lane”,”city”:”Van Horne”,”state code”:”IA”,”state”:”Iowa”,”zip code”:”52346”}"
                ]

I am currently developing an Angular4 application where I receive response data in the form of an array containing strings of objects. My challenge is to display each object individually using ngFor directive. However, I am facing difficulty in displaying the data as the object properties are in string format. Below is my problem:

"options": [
                    "{“street”:”3104 Doctors Drive”,”city”:”Los Angeles”,”state code”:”CA”,”state”:”California”,”zip code”:”90017”}",
                    "{“street”:”3358 Cinnamon Lane”,”city”:”San Antonio”,”state code”:”TX”,”state”:”Texas”,”zip code”:”78212”}",
                    "{“street”:”573 May Street”,”city”:”Harold”,”state code”:”KY”,”state”:”Kentucky”,”zip code”:”41635”}",
                    "{“street”:”2836 Cantebury Drive”,”city”:”New York”,”state code”:”NY”,”state”:”New York”,”zip code”:”10013”}",
                    "{“street”:”2935 Kidd Avenue”,”city”:”St George”,”state code”:”AK”,”state”:”Alaska”,”zip code”:”99591”}",
                    "{“street”:”3676 Spirit Drive”,”city”:”Jacksonville”,”state code”:”FL”,”state”:”Florida”,”zip code”:”32220”}",
                    "{“street”:”2134 Shobe Lane”,”city”:”Moody”,”state code”:”AL”,”state”:”Alabama”,”zip code”:”35004”}",
                    "{“street”:”3614 Rhapsody Street”,”city”:”Aiea”,”state code”:”HI”,”state”:”Hawaii”,”zip code”:”96701”}",
                    "{“street”:”1756 Forest Drive”,”city”:”Ashburn”,”state code”:”VA”,”state”:”Virginia”,”zip code”:”22011”}",
                    "{“street”:”686 Upland Avenue”,”city”:”Toledo”,”state code”:”OH”,”state”:”Ohio”,”zip code”:”43609”}",
                    "{“street”:”574 Copperhead Road”,”city”:”Abercrombie”,”state code”:”ND”,”state”:”North Dakota”,”zip code”:”58001”}",
                    "{“street”:”3106 Tecumsah Lane”,”city”:”Van Horne”,”state code”:”IA”,”state”:”Iowa”,”zip code”:”52346”}"
                ]

This is the array that needs to be displayed. How can I implement the code for this array in Angular4?

Answer №1

var addressOptions = [
"{“street”:”3104 Doctors Drive”,”city”:”Los Angeles”,”state code”:”CA”,”state”:”California”,”zip code”:”90017”}",
"{“street”:”3358 Cinnamon Lane”,”city”:”San Antonio”,”state code”:”TX”,”state”:”Texas”,”zip code”:”78212”}",
"{“street”:”573 May Street”,”city”:”Harold”,”state code”:”KY”,”state”:”Kentucky”,”zip code”:”41635”}",
"{“street”:”2836 Cantebury Drive”,”city”:”New York”,”state code”:”NY”,”state”:”New York”,”zip code”:”10013”}",
"{“street”:”2935 Kidd Avenue”,”city”:”St George”,”state code”:”AK”,”state”:”Alaska”,”zip code”:”99591”}",
"{“street”:”3676 Spirit Drive”,”city”:”Jacksonville”,”state code”:”FL”,”state”:”Florida”,”zip code”:”32220”}",
"{“street”:”2134 Shobe Lane”,”city”:”Moody”,”state code”:”AL”,”state”:”Alabama”,”zip code”:”35004”}",
"{“street”:”3614 Rhapsody Street”,”city”:”Aiea”,”state code”:”HI”,”state”:”Hawaii”,”zip code”:”96701”}",
"{“street”:”1756 Forest Drive”,”city”:”Ashburn”,”state code”:”VA”,”state”:”Virginia”,”zip code”:”22011”}",
"{“street”:”686 Upland Avenue”,”city”:”Toledo”,”state code”:”OH”,”state”:”Ohio”,”zip code”:”43609”}",
"{“street”:”574 Copperhead Road”,”city”:”Abercrombie”,”state code”:”ND”,”state”:”North Dakota”,”zip code”:”58001”}",
"{“street”:”3106 Tecumsah Lane”,”city”:”Van Horne”,”state code”:”IA”,”state”:”Iowa”,”zip code”:”52346”}"
];
  
  var newAddresses = [];
  
  addressOptions.map((addressObj) => {
let data = addressObj.replace(/”/g, '"');
data = data.replace(/“/g, '"');
newAddresses.push(JSON.parse(data));
})
    
   console.log('newAddresses', newAddresses);

Answer №2

To make your data compatible with *ngFor, ensure you correctly parse it using JSON.parse. Any problems you encounter are probably related to syntax errors in your parsing process. Focus on fixing the parsing issue in order for *ngFor to function properly. The purpose of *ngFor is to handle exactly this type of iteration once the parsing is resolved.

Answer №3

If you encounter a problem with the string you are attempting to parse, consider utilizing a JSON parser and formatter available online. Simply paste your JSON object into the tool at the website provided below.

This will allow you to easily identify and rectify any issues within your data.

Alternatively, as a less optimal solution, you can manually construct your object through string manipulation. By using functions like string.split on specific characters, such as quotation marks, you can generate an array of strings. This array can then be transformed into a key-value pair object for further processing.

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

Using TypeScript to Infer Types in a Wrapper Function

When it comes to functions related to database operations, I have a handy utility/wrapper function that handles specific tasks. It takes a function fn of type Promise<PromiseReturnType<GENERIC>>, performs some preliminary actions (such as check ...

Utilizing the Download Attribute in HTML 5 with iPhone Devices

Is there a way to download and view files such as PDFs, Word docs, and JPGs on an Ionic progressive web app without leaving the current page? I've tried using the html5-Download attribute on Android, but it doesn't work properly on iPhone. Any su ...

Using a custom validator in Angular that accepts an array as input

My special code: <input mdInput [mdAutocomplete]="auto" [(ngModel)]="formData.areaName" (keyup)="updateFilteredAreas(formData.areaName)" class="form-control {{areaName.errors ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

Guide to incorporating external JSON data into a Select dropdown in Angular 7

Issue : How to populate JSON values retrieved from a REST API into a Select statement? team.component.html <mat-select placeholder="Select Name" [(ngModel)]="name"> <mat-option *ngFor="let currentName of nameValuesArray" [value]='currentN ...

Leveraging TypeScript Record for creating a limited set of object keys

Is it feasible to create a Record that maps selected keys from one object to another? I am attempting to map Google's libphonenumberCountryCode options to my custom formatting objects. Currently, I have: const countryOptions: Record<CountryCode, Co ...

Utilize tree-shaking functionality within your TypeScript project

In the process of developing a TypeScript telemetry library using OpenTelemetry, I am exploring ways to incorporate tree-shaking to allow consumers to selectively import only the necessary modules and minimize the overall bundle size. The project directory ...

Error: In Typescript, it is not possible to assign the type 'false' to type 'true'

Currently, I am exploring Angular 2 and encountered a situation where I set the variable isLoading to true initially, and then switch it to false after fetching required data. However, upon executing this process, I encountered the following error message: ...

Tips for creating a Cypress command chain that includes parameters

Looking for an expander with its caption to click on it. Successfully working: cy.get('[caption="Radio Button"] > .expander-container').click(); Want to turn this into a command. Cypress.Commands.add('findExpanderByName', ...

Combining PowerShell with Angular for seamless integration

As I work on the frontend of a web application using Angular, my goal is to seamlessly integrate it with an existing 'backend' powered by Powershell. Originally part of a desktop app, I now aim to repurpose the Powershell backend for use in a web ...

Changing the dropdown value by clicking the previous and next buttons in Angular 2

I need to implement a feature in Angular 2 where the default date displayed in a dropdown is the current year. Additionally, when the "Prev" button is clicked, the selected year value in the dropdown should decrease by one. // Our root app component imp ...

Running multiple instances of an Angular2 module on a single page using Bootstrap

I have a unique situation where my web forms application dynamically loads User controls onto a page using configurations, similar to a CMS with re-usable widgets. I'm interested in implementing one of these user controls as an Angular2 component. &l ...

Utilizing Angular 2 to activate an input field within a component based on the value of a checkbox in the template

Apologies for the somewhat vague question title, I couldn't come up with a better one. I am currently working on a function that is triggered by a checkbox's true/false value: setReward(): void { const rewardControl = this.myFormLost.get(' ...

Tips for effectively mocking a service class in a hybrid Angular project to facilitate unit testing

I'm currently working on a hybrid Angular project, but I've encountered some challenges with unit testing. Despite trying out this solution, it doesn't seem to be effective for my particular project. I keep receiving an error when running ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

I encountered an error while working with Node.js where it stated that `readFileSync` is

In my current web app project, I am utilizing Angular 2, typescript, Node.js, and Visual Studio. The task at hand is to access a file stored in the wwwroot folder. To accomplish this, I have devised the following class: ///<reference path="../../node_m ...

What direction does Angular2 animation rotate in?

In my Angular2 application, I am trying to create a menu icon that rotates clockwise when shown. The desired animation is for it to rotate from -360 degrees to -180 degrees when displayed and from -180 degrees to 0 degrees when hidden. Currently, the anim ...

Steps for sending a POST request with data from Ionic 4 to Django Rest Framework

I am attempting to make a post request from my ionic V4 project to the Django backend website. Below is the code I am using: Django Code models.py Here is the class where I need to post data to: class Item(models.Model): (...) serializers.py - thi ...

Angular: Determining when a form has returned to its original state

My current task involves working with a reactive form that comes with default values. I need to figure out how to prevent the user from saving changes until they have modified something, and then revert back to the initial state. Although I can subscribe ...

Watching multiple Angular libraries for changes and serving to a separate application on the go

Currently, I am working on developing three Angular libraries that will be consumed by another main application. My goal is to have live rebuilding for the libraries while my main app imports and runs them simultaneously. This way, I can achieve live reloa ...