What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single random item from the same JSON file on the homepage - using *ngFor ends up showing all items instead.

Below is a snippet of my code:

export class DashboardComponent implements OnInit {

    nfts: any;
    constructor(
        private http: HttpClient,
    ) {

    }

    ngOnInit(): void {
        this.getNfts()
    }

    getNfts() {
        this.http.get('https://63bd1526fa38d30d85d88179.mockapi.io/NFT/v1/metadata').subscribe((data) => {
            this.nfts = data
        })
    }

}

// HTML

            <div class="card cards card-p" *ngFor="let nft of nfts">
                <img src="{{nft.image}}" class="card-img-top">
                <div class="card-body">
                    <h4 class="nft-title">{{nft.name}}</h4>
                    <a class="nft-collection mb-3" routerLink="/">NFT collection</a>
                    <p>Price: <span>300</span></p>
                    <button class="button heart text-end"><i class="fa-solid fa-heart"></i></button>
                    <a routerLink="/nft-details/:id" class="stretched-link"></a>
                </div>
            </div>

I would greatly appreciate any assistance with this challenge! Thank you in advance!

Answer №1

If you're looking to showcase a single random element from an array, you can achieve this by utilizing "Math.floor(Math.random() * this.nfts.length)" to select a random element and display it.

As a result, the HTML structure will resemble the following:

<div class="card cards card-p">
  <img src="{{nfts[randomIndex].image}}" class="card-img-top">
  <div class="card-body">
    <h4 class="nft-title">{{nfts[randomIndex].name}}</h4>
    <a class="nft-collection mb-3" routerLink="/">NFT collection</a>
    <p>Price: <span>300</span></p>
    <button class="button heart text-end"><i class="fa-solid fa-heart"></i></button>
    <a routerLink="/nft-details/:id" class="stretched-link"></a>
  </div>
</div>

The associated Javascript code is as follows:

export class DashboardComponent implements OnInit {
    nfts: any;
    randomIndex = 0;
    constructor(
        private http: HttpClient,
    ) {

    }

    ngOnInit(): void {
        this.getNfts()
    }

    getNfts() {
        this.http.get('https://63bd1526fa38d30d85d88179.mockapi.io/NFT/v1/metadata').subscribe((data) => {
            this.nfts = data
            this.randomIndex = Math.floor(Math.random() * this.nfts.length)
        })
    }

}

Answer №2

Implement the Object.map method to iterate through elements with matching syntax.

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

What is the best way to include npm dependencies from multiple registries in the package.json file?

Within my package.json file, I have specified dependencies, one sourced from the public registry and another from a private registry (specifically Artifactory). "dependencies": { "vue": "^2.4.4", //public registry "ce-ui": "http://myartifa ...

Guide on how to loop through a JSON request using a mule integration framework

First of all, I want to express my gratitude for the incredible work you are doing. I have been increasingly drawn to your website, and now I find myself in need of assistance for the first time. Currently, I am exploring mule esb and attempting to iterat ...

What is the best way to inject a custom Angular service into a test in TypeScript without needing to mock it?

I have defined my modules and tests as shown below, but I encounter an issue when attempting to inject ContentBlocksService into the beforeEach(mock.inject((ContentBlocksService)... statement. It shows an error message saying Unknown provider ContentBlocks ...

Tackling the white-source security problem in npm libraries

A security advisory from White-source has identified high vulnerability issues with certain libraries used in your repository, specifically with yargs-parser: 1. build-angular-0.13.8.tgz (Root Library) node-sass-4.11.0.tgz sass-graph-2.2 ...

Encountering a blank page and slow loading when launching the VSCode debugger using VS Code version 1.76.1 and Chrome 111

Recently, I've encountered a problem with the VS Code debugger while trying to debug an Angular application. I created a new Angular app using the ng new command and made some changes to the ngOnInit function. When attempting to start the Chrome deb ...

Developing web applications using AngularJS and Web API allows for customization of error handling by utilizing

Here I have a simple form that includes only one input field for the user's name. However, I want to make sure that there are no duplicate entries in the table. I can easily check this on the server side and send a custom message in the response head ...

What is the best way to showcase Json API content on an HTML page?

I possess a strong proficiency in html and css, however I lack experience in utilizing javascript. My aim is to showcase the date received from an API onto an html page Despite several attempts, I have not been able to achieve success yet. var getJSON ...

The error message "Uncaught ReferenceError: process is not defined" indicates that

While attempting to execute my code, I encountered the following error in the React console: An uncaught ReferenceError: process is not defined I am seeking guidance on resolving this error. Any assistance would be greatly appreciated. ...

What is the best way to assign SnapshotChanges to an Observable Firebase variable?

I'm facing an issue where I can't access the id of a document even though it's visible when printing the object this.ressobj. However, when I try to use ressobj.id_doc in the card, the id of the document is not visible. this.ResColeccion ...

Understanding the implementation of setters in JavaScript: How are they utilized in Angular controllers?

After learning about getters and setters, I came across an example that clarified things for me: var person = { firstName: 'Jimmy', lastName: 'Smith' }; Object.defineProperty(person, 'fullName', { get: function() ...

AngularJS end-to-end testing using Testacular causes browser disconnections for all tests

I'm currently working on setting up e2e tests for my AngularJs project using testacular. I've successfully launched a node.js-based web server and can see the files being sent when a URL is loaded. I am also able to view the expected results in m ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

The module imported by Webpack appears to be nothing more than a blank

I am attempting to integrate the "virtual-select-plugin" library into my Typescript project using webpack. Unfortunately, this library does not have any type definitions. Upon installation via npm, I encountered the following error in the browser: TypeErro ...

Yelp API call resulting in an 'undefined' response

When attempting to make an API call using the yelp-fusion, I noticed that the logged result is showing as undefined. It seems like this issue might be related to promises or async functions. It's important for me to maintain this within a function sin ...

Tips for Implementing a JSON Web Service Call in a Web Browser

Recently, I have been facing a dilemma with a web service that returns JSON string. My goal is to call this web service directly in the browser without relying on "Invoke". The format I have been using for calling is as follows: http://localhost/Webservic ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

The issue of Angular 12 Bootstrap 5 ngFor accordion remaining open persists

I am currently working on implementing a ngFor dropdown accordion list using Angular 12 and bootstrap 5. However, I am facing an issue where the accordions are staying open and not closing as expected. If anyone has any insights on how to resolve this and ...

Is there a way to import content from a .json file in webpack5?

Currently, I am facing an issue with webpack5 where I am unable to import .json files. From my understanding, there should be no need to install a loader for importing json files. However, out of curiosity, I did install "json5-loader" and defined the foll ...

AngularJS encounters a blank error response

Struggling to implement basic REST services from Angular, but receiving an empty error response every time. When I directly open the index.html on my PC (not sure if this is causing the issue) and click 'login', the controller gets called: $sco ...

The functionality of ng-click or ng-href within a repeated table row is not functioning as expected

The following code snippet is from the HTML page: <tr ng-repeat="res in result" ng-click='go()'> <td>{{res.value1}}</td> <td>{{res.value2}}</td> <td>{{res.value3}}</td> <td>{{res.v ...