Display items in a visual format when they're contained within a JSON or object with NativeScript

Here is a snippet of JSON data:

{
    "StatusCode": 0,
    "StatusMessage": "OK",
    "StatusDescription": [
        {
            "pharmacy_id": "011E752345553380ABC13FFA163ECD15",
            "pharmacy_name": "Pharmacy",
            "lastUpdated": "2019-12-03T11:15:26.510Z",
            "products": [
                {
                    "productID": "11AA016CBEFFE8B29B46E8393535C49F",
                    "quantity": 1,
                    "product_name": "BETADINE",
                    "price": 10
                }
            ],
        },
        {
            "pharmacy_id": "011E762345552280FBC13FFA163ECD10",
            "pharmacy_name": "Test Pharmacy",
            "lastUpdated": "2019-12-03T13:40:55.759Z",
            "products": [
                {
                    "productID": "11BA016CBEFFE8B29B46E8393445C49F",
                    "quantity": 4,
                    "product_name": "EUCARBON",
                    "price": 10
                },
                {
                    "productID": "11BA016CBEFFE8B29B46E8393532C49F",
                    "quantity": 2,
                    "product_name": "ALMACINE",
                    "price": 10
                },
                {
                    "productID": "22BA016CBEFFE8B29B46E8393555C49F",
                    "quantity": 2,
                    "product_name": "BUPRENORFIN",
                    "price": 10
                }
            ],
        },
          .....

    ]
}

I'm looking to display the product name, quantity, and price in the view.

The code below retrieves the data from an API:

public items: Receta;
    getall() {
        this.WS.history().subscribe(
            items => {
                this.items = items;
                console.log('itemsssssssssssssss', items) // show JSON
                console.log('itemsssssssssssssss.products', items.products) // show undefined
            },
            err => console.error('err', err),
            () => console.log('error')
        );     
    }

In the HTML file, only the pharmacy names are currently being displayed, but I would like to include products for each pharmacy as well.

<StackLayout *ngFor="let item of items; let i = index;" padding="10">
                        <GridLayout columns="*" rows="auto" style="padding: 10%;">
                            <Label [text]="item .pharmacy_name" class="list-group-item-heading"
                                style="width: 60%; font-size: 14px; text-align: left;" row="0" col='0'
                                horizontalAlignment="left"></Label>
                        </GridLayout>
    </StackLayout>

If you have any suggestions on how to display both pharmacies and their respective products in the view, please share!

Answer №1

Your issue lies here:

console.log('itemsssssssssssssss.products', items.products) // displays undefined

The items JSON does not contain any products

To rectify this, you can implement the following logic

const newItemsArray = [];
items.StatusDescription.forEach((st) => {
     newItemsArray = newItemsArray.concat(st.products);
})

The newItemsArray now holds all the products. You have the option to use the rxjs map operator to return this array.

Alternatively, you could declare newItemsArray as a public member of your class and utilize it directly.

   <StackLayout *ngFor="let item of newItemsArray ; let i = index;" padding="10">
                        <GridLayout columns="*" rows="auto" style="padding: 10%;">
                            <Label [text]="item.pharmacy_name" class="list-group-item-heading"
                                style="width: 60%; font-size: 14px; text-align: left;" row="0" col='0'
                                horizontalAlignment="left"></Label>
                        </GridLayout>
    </StackLayout>

To access the products, you will need another ngFor loop like this

  <StackLayout *ngFor="let item of items; let i = index;" padding="10">
                        <GridLayout columns="*" rows="auto" style="padding: 10%;">
                            <Label *ngFor="let product of item.products; let i = index;" [text]="product.product_name" class="list-group-item-heading"
                                style="width: 60%; font-size: 14px; text-align: left;" row="0" col='0'
                                horizontalAlignment="left"></Label>
                        </GridLayout>
    </StackLayout>

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

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

establishing a header for a curl request on an external domain

I'm currently working on updating some fields on a remote site using curl. So far, I have successfully logged into the remote site and fetched the csrf token required for the curl request. However, I am facing difficulties in setting the header parame ...

Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below: // base.js module.exports = function BaseClass () { // ... ... }; M ...

Struggling to create a SVG Line with DOM Manipulation in Typescript

I'm having trouble adding an SVG element to my div using the appendChild function in TypeScript. I want to add a line inside the SVG, but for some reason, I can't see the line output on my browser. There are no errors showing up either. Please he ...

Encountered an error while trying to access the 'deletePostById' method in Angular due to undefined properties

Help needed: TypeError regarding 'deletePostById' What's causing the issue in my code? HTML <div class="row post" *ngFor="let post of posts"> <div *ngIf="isAdminIn" ngbDropdown class="float- ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Defining ReactNode as a prop in a TypeScript React component: A comprehensive guide

Is there a way to create a React component in TypeScript that accepts another React component as a prop? I am attempting to write the following code: const MyComponent = () => ( <span>Hello</span> ); // when trying this, I get an error m ...

Error loading personalized SVG on mat-icon

I have been attempting to load a custom SVG using the MatIconRegistry within my component. Here is the code snippet I am trying: constructor(fb: FormBuilder, private matIconRegistry: MatIconRegistry, private domSanitizer: DomSanitizer) { thi ...

What are the steps to confirm that a file has been successfully downloaded using TestCafe?

Imagine needing to confirm the download of a file by first downloading it and then checking if the file is in the designated folder. ...

ThreeJS is having trouble loading JSON files

After reading through this particular question, I unfortunately did not find the help I was seeking. Here's my process: First, I export a model from Cinema 4D to .obj format. Then, I import the obj file into www.threejs/editor. I fill in all the nec ...

Utilizing a mathematical equation stored in JSON within a JavaScript environment

I'm in the process of creating a conversion calculator and I want to save the formulas and references in JSON format. Unfortunately, I'm uncertain on how to interpret the variable as a mathematical operation. JSON var JSON = { "conversio ...

In Typescript, invoking toString() does not alter the data type of the property

When I encounter the error in the valorControlo property, it states: The 'valorControlo' property does not exist on the type 'string'. Even after adding the toString(), the issue persists. Here is the snippet of code: const [isBarExten ...

Tips for stopping a component from reloading when a query parameter changes in Angular 2

this.router.navigate(['CurrentComponent', {id: this._id, param1: value}]); The provided code snippet successfully modifies the query parameters in the current URL. However, it causes the component to reload every time the URL is updated. Is ther ...

I am currently working on obtaining images that are saved by their URL within a PHP file. These images are located within a directory named "images."

My code is incomplete and not functioning as expected. $.get("museums.php",function(data,status){ var response=''; //console.log(data); var json = $.parseJSON(data); museums = json.museums; for(let m in museums) { $("#na ...

Modify/remove table using a popup window

My goal was to include edit and delete buttons within a table. When these buttons are clicked, a popup window opens allowing us to modify the values and then update them in the table using Angular. ...

Is there a way to delay until the result is obtained from setInterval and then return it from the customized pipe in Angular?

I've created a custom pipe that recalculates the remaining time of an appointment date every second and returns it to the HTML. However, I'm unable to await the result. import * as moment from 'moment'; @Pipe({ name: 'appointme ...

Discovering the source of the 'Navigation triggered outside Angular zone' error, if feasible

Whenever I run my Angular 11 application, a warning pops up in the console: 'Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'? core.js:27937 I am curious if there is a method to track do ...

Tips for invoking a .aspx document within a .ascx file using json and ajax technology

Currently in the process of developing a large website using ASP.net and either vb.net or C#, I am facing a challenge where upon clicking a button, specific text should be displayed on the site. To achieve this, I plan to utilize ajax/json to call a .aspx ...

Analyzing a string that may contain two JSON objects

Is there a way to parse and extract data from strings like the ones below into JSON objects? "[{"months": 12, "product": "car"}, {"months": "12", "product": "bike"}]" "[{"months": 12, "product": "car"}]" I am seeking a technique to determine the number ...

A function in Typescript is created to handle diverse input types in a generic manner

My goal is to create a function that can handle various input types for abstraction purposes. type ContentA = string type ContentB = number type InputA = { name: 'method_a' content: ContentA } type InputB = { name: 'method_b' con ...