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

Twitter typeahead not functioning properly when used in conjunction with ajax requests

I have limited experience in the frontend world and I'm currently working on getting this to function properly. $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 6 }, { source: function (query, ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

What are the steps to resolve warnings in an imported json file?

I am working on a Vue project where I have imported a JSON file into my TypeScript script using import jsonData from '@/assets/data1.json'; Although the data is accessible and functions correctly, I am encountering numerous warnings during the b ...

A fresh perspective on incorporating setInterval with external scripts in Angular 7

Incorporating the header and footer of my application from external JavaScript files is essential. The next step involves converting it to HTML format and appending it to the head of an HTML file. private executeScript() { const dynamicScripts = [this.app ...

Retrieve the user information from Auth0 within the NestJS application

I am currently working on implementing Auth0 authorization in NestJS, but I am unsure of how to retrieve the user's data within the callback URL handler. In a normal express function, this issue could be resolved using the following code. The passpor ...

Python encounters a Json Decoder Error while trying to read data from a JSON file

Currently, I am attempting to access a 17MB JSON file stored in Google Drive within collaboratory. Here is the code snippet I have been using: import json with open('GOOGLEDRIVE_FILEPATH/FILE_NAME.json',encoding="utf-8-sig") as f: dat ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Expanding MySQLi: Adding additional and nested results

Struggling to figure out the correct terms for my query. Looking for guidance on how to pull data from two tables in a database: tableA (house sale records) and tableB (realtor visit records). I want to search by owner ID in tableA and retrieve all their h ...

Creating definitions for generic static members within a third-party module

There is a 3rd party module with the following structure: export class Container{ static async action() { return {...} } constructor(params = {}) { // ... } async doSomething(params = {}) { // ... } } I am looking to de ...

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

callbacks in amazon-cognito-identity-js

When working with amazon-cognito-identity-js, I encountered an issue with the callback function. This is what it currently looks like: cognitoUser?.getUserAttributes((err, results) => { if (err) { console.log(err.message || JSON.stringify(err)); ...

Obtain JSON data response in PHP with the help of jQuery

Below is the code I am using to make an AJAX call and retrieve data from another PHP file: $.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km}, function(data){ $('#fare'). ...

A practical method for restructuring or dividing a string containing JSON entries

Within my dataset, I've got a string comprising JSON entries linked together similar to the following scenario. val docs = """ {"name": "Bilbo Baggins", "age": 50}{"name": "Gandalf", "age": 1000}{"name": "Thorin", "age": 195}{"name": "Balin", "age" ...

Prevent auth0 express middleware from causing server crashes by handling failures silently

I am currently integrating auth0 into a node project for authentication using JWTs. Each request to an authenticated endpoint requires a token, and auth0 provided me with this middleware function: import {auth} from 'express-oauth2-jwt-bearer'; i ...

Retrieving data stored in a JSON file and loading it into a Backbone model

I've come across an issue with my code where the data from my static json file isn't being pulled into my model. I suspect that using a static json file might be causing this problem, but I haven't been able to find any documentation address ...

Is there a way to create fresh instances of a class using Injector rather than utilizing a singleton pattern?

In my Angular application, I am working with two injectable classes. @Injectable() class B {} @Injectable() class A { constructor(b:B) { } } My goal is to make class A a Singleton and class B a Transient. I recently discovered that I can utilize Ref ...

Efficiently managing various, yet closely related routes in Angular

Is it possible to have the following link item be active for multiple links? <li class="nav-item"> <a class="nav-link" routerLinkActive="active" [routerLink]="['/testGame/list']"><i class="icon-game-controller"></i&g ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

Tips for deserializing a JSON object with an object or an array of objects

I am facing a challenge in deserializing the JSON response received from the ARIN whois REST API. As someone new to JSON, I believe they may be returning two different schemas based on the results, making it difficult for me to parse the data correctly. W ...

Is there a way to ensure that the onChange event of ionic-selectable is triggered twice?

I've been working with an ionic app that utilizes the ionic-selectable plugin, and for the most part, it's been running smoothly. However, I encountered a rare scenario where if a user on a slow device quickly clicks on a selection twice in succe ...