How to retrieve an array stored within a JSON object

I am trying to access a specific array within an object from a JSON file. Here is the snippet of the data I'm dealing with:

best-sellers": [
    {
      "title": "Chuteira Nike HyperVenomX Proximo II Society",
      "price": 499.90,
      "installments": {
        "number": 10,
        "value": 49.90
      },
      "high-top": true,
      "category": "society",
      "image": ""
    },
    {
      "title": "Chuteira Nike HyperVenom Phantom III Cano Alto Campo",
      "price": 899.90,
      "installments": {
        "number": 10,
        "value": 89.90
      },
      "high-top": true,
      "category": "campo",
      "image": ""
    }
}
]

This is how my component code looks like:

   ngOnInit(): void {
      this.service
      .lista()
      .subscribe(chuteiras =>{
        this.chuteiras = chuteiras;
      })
  }

and in my template, I have written:

<div *ngFor="let chuteira of chuteiras.best-sellers">

However, Angular does not seem to recognize `best-sellers" and it throws the following error:

Cannot read property 'best' of undefined

Answer №1

To access the elements, bracket notation is the way to go.

<div *ngFor="let sneaker of sneakers["top-picks"]">

Answer №2

While that approach may work, Angular 6 introduced a more straightforward solution. When I encountered this issue, I initially tried the suggested method but it did not yield the desired results. After conducting some research and implementing my own modifications, I eventually arrived at a different solution.

1. Begin by creating a function to fetch JSON data, utilizing a web API in my case:

getTrending() {
    return this.http.get(
${this.api_key}); }

2. Invoke the function within a service, importing it into the component and adding the following code snippet:

showPopular(): void {
         this.api.getTrending().subscribe((data:  Array<object>) => {
          this.list  =  data['results'];
          console.log(this.list);
       });
      }

By doing so, the 'data' variable is able to access only the specific information needed.

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

Convert TypeScript model to JSON while excluding properties with null values

When working with an Angular 4 App and a typescript model, I have defined a Person class as follows: export class Person{ fname:string, lname?:string } The 'lname' property in the model is optional. To populate the model in a component, I u ...

Utilizing *ngfor in Angular 7 to Group and Display Data

I currently have incoming data structured like this in my Angular application Visit this link to see the data format https://i.stack.imgur.com/jgEIw.png What is the best way to group and sort the data by State and County, and present it in a table as sh ...

Upcoming Authentication Update: Enhancing User Profile with Additional Data Points

I recently encountered an issue with my typescript application that uses Next Auth v4 along with GithubProvider and MongoDBAdapter. I needed to add a new field called role to the User schema. Researching online, most solutions suggested adding a function ...

Invoke the method saved as a class attribute

Within my codebase, there exists a class named Process. This class has a constructor that takes in a type of object () => void. Initially, everything seemed to be working perfectly fine when I passed this object into the class. However, issues arose whe ...

GoLang Struct JSON conversion issue

I have a struct called "Sim" that I need to convert into JSON after populating it with data. When I print the variable s, it displays the correct information, but when I print data, it appears blank. Can someone help me figure out how to properly convert ...

Creating a dynamic selection in Angular without duplicate values

How can I prevent repetition of values when creating a dynamic select based on an object fetched from a database? Below is the HTML code: <router-outlet></router-outlet> <hr> <div class="row"> <div class="col-xs-12"> & ...

The Android value with the type java.lang.String cannot be transformed into a JSONArray

My project uses WCF to retrieve records from a database and returns them in JSON format as shown below: {"GetNotesResult":"[{\"ID\":1,\"Title\":\"Note 1\",\"Content\":\"Hello Vu Chien Thang\",\"Create ...

Add a hash to the file name of the JSON translation asset

To prevent caching issues, I choose to store my translation files as JSON in /src/assets/i18n. To achieve this in Angular, I am looking for a way to add a unique fingerprint or hash to the filename of the file and use that hashed name when retrieving the ...

Using JSON / jQuery: How to Handle XML Data in the Success Function of an AJAX Post Request

Greetings! I am currently performing an ajax post through a JSP. The JSON data is being sent in string format (parsed using parseJSON, then converted back to a string using JSON stringify). The post operation functions correctly. However, my query lies in ...

Error retrieving content from website: Failed to connect to http://roblox.plus:2052/limiteds

Whenever I try to execute the code below, an error message pops up: file_get_contents(): failed to open stream: Connection refused $file = file_get_contents('http://roblox.plus:2052/limiteds'); $decode = json_decode($file, false); foreach ...

Learn how to effectively deserialize a JSON string with an array into a specific class using GSON

I need help on how to serialize and deserialize this specific JSON format into a Java class. Anyone have any code samples or suggestions? [ { "topic": "this is my topic" }, [ { "name": "John" }, { ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

What is the best way to store numerous objects in an array at once?

Upon clicking the save button, I encounter this object: {description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "2", hr_id: 72, …} However, every time I click on save, a new object ...

What is the best way to send data to a child component in Angular, including components that can be

There are two components in my project: the parent component and the child component, each with their own unique markup. It is crucial for this example that the child component fetches its own data to render and not be provided by the parent. Currently, th ...

Enhance the parsed struct by adding a new variable called json

As I work with some static data related to a list of "Badges," my goal is to parse it using JSONDecoder. However, I encountered an issue when trying to add a new state that wasn't included in the JSON data. Adding this variable to the Badge struct led ...

Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet: class Salutation { message: string; constructor(text: string) { this.message = text; } greet() { return "Bonjour, " + this.message; } } class Greetings extends Salutation { ...

Is there a specific function that is triggered upon the successful completion of a subscription process?

I am facing an issue with the code below. The navigation is happening when a customer is created, instead of waiting for the address to be created successfully. Any assistance on this matter would be greatly appreciated. createCustomer(model: any) { ...

Excessive string length within a JSON array results in a 400 Bad Request error on a .NET Core Web API

Within my JavaScript application, I am utilizing the fetch API to send an array that contains a lengthy string to a .NET Core Web API. The structure of this data looks like: "FirstName LastName (Country) TEXT INFORMATION: ^MOM?ROVAL LETTER REQUI ...

The type 'ElementClass' is lacking several key properties, specifically context, setState, forceUpdate, props, and refs

I'm currently developing a web application using NextJS with Typescript. During my testing phase with Jest+Enzyme, I encountered the following error message: ** Test suite failed to run TypeScript diagnostics (customize using `[jest-config].globals. ...

I successfully added JSON data to the postgresql query, however the resulting output was not as anticipated

I've been attempting to load JSON data into a postgresql table, but I'm encountering some issues. JSON DATA: { "wsgi.multiprocess": true, "HTTP_REFERER": "http://localhost:9000/" } To accomplish this, I am following these steps: CREATE TABLE ...