Html Showing two objects

I am working with an object array that is being sent from an API. Right now, it is displaying the index position, but I actually want to display the object key and its corresponding value. I believe I may be mapping the object key incorrectly. Could anyone provide assistance with this issue?

getFav(): void {
                this.Shared.getFav().subscribe(

                data => {
                    this.fave = data.message;
                    Object.keys(this.fave).map((keyName) => {
                    return {id: keyName, product: this.fave[keyName]};
                    });
                }
                );
                }
<div class="uk-width-small" uk-dropdown>
                        <div class="uk-dropdown-grid uk-child-width-1-1@m" uk-grid>
                        <div *ngFor="let fav of fave | keyvalue" >
                            <span>{{fav.value}}</span>
                            <span>{{fav.key}}</span>
                        <a href="{{fav.key}}"><li>Buy On amazon<br/>
                        </li></a>
                    </div>
                </div>
            </div>

https://i.sstatic.net/SDDOd.png

The current response from my API is showing the index positions. Do I need to make changes on the backend or can I adjust something on the frontend to only display the title key and its value? https://i.sstatic.net/wxDLD.png

Answer №1

When dealing with fav.value, remember that it is an object! You need to specify which key you want to retrieve, such as fav.value.id or fav.value.title

<div class="uk-width-small" uk-dropdown>
    <div class="uk-dropdown-grid uk-child-width-1-1@m" uk-grid>
        <div *ngFor="let fav of fave | keyvalue" >
            <span>{{fav.value.title}}</span>
            <span>{{fav.key}}</span>
            <a href="{{fav.key}}">
                <li>Buy On amazon<br/></li>
            </a>
        </div>
    </div>
</div>

Answer №2

One issue lies in your utilization of the Object.keys() method on the complete array, resulting in only the indexes and object being returned. To rectify this, you must apply it to each individual object within the array to achieve the desired outcome.

Answer №3

Perhaps you should consider modifying the function getFav

let newFaves=[]; //declaring a global variable like this at the top of the ts file

getFav(): void {
  this.Shared.getFav().subscribe(
    data => {
      this.fave = data.message;
      this.newFaves =this.fave.map((item) => {
        return {id: item.id, product: item.title};
      });
    }
  );
 }

Next, in your HTML:

<div class="uk-width-small" uk-dropdown>
          <div class="uk-dropdown-grid uk-child-width-1-1@m" uk-grid>
          <div *ngFor="let fav of newFaves | keyvalue" >
            <span>{{fav.value}}</span>
            <span>{{fav.key}}</span>
      <a href="{{fav.key}}"><li>Buy On amazon<br/>
      </li></a>
    </div>
  </div>
</div>

Answer №4

Utilizing the keyvalue pipe eliminates the need to modify the getFav function.

The value extracted with the keyvalue pipe is an entire object

(for example: {id: 20, title: '...', image: '...'})

Therefore, you must specify which property you wish to access in Angular.

 <span>{{fav.value.id}}</span>
 <span>{{fav.value.title}}</span>
 <img [src]="fav.value.image"/>

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

I am experiencing an issue in my Supabase project where user data from the authentication system is not being seamlessly integrated into the profiles table in real-time

``I have noticed that user information stored in the auth section of my Supabase project is not automatically added to the profiles table in real-time. I am looking for guidance on how to configure this aspect of the Supabase project. Can you please advise ...

`Navigating seamlessly across multiple Angular applications`

Contemplating the use of Angular in a corporate setting, I am thinking ahead to having multiple applications. Does Angular support the use of multiple applications and sharing components? For instance, can I share a Navigation component? Update (2/1/19): ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

Implement the Promise return type for a function in Angular

I'm looking to modify the following method to change the return type to a Promise or Observable: basketItemNodes: TreeNode[] = []; getBasketItems() { this.basketService.getAllBasketItems() .subscribe( res => { this.basketItemN ...

When attempting to build the iOS app with Ionic, the error "Unable to access property toLowerCase of undefined" is

When attempting to build ios in Ionic3 using the command: ionic cordova build ios, I encounter the error "Cannot read property toLowerCase of undefined". Below is the log output with the --verbose flag: > ionic-app-scripts build --target cordova --pla ...

TypeScript Generic Extended React Component

I am trying to enhance the React Component class with my own custom class. export class CustomReactComponent<P,S> extends React.Component<P,S> { public doSomeStuff() { alert("Custom React Component"); } } export class MyCompon ...

Organizing string enum in Typescript and AngularJS - Tips and Tricks

In my Typescript file, I have defined an enum called PriorityLevel: enum PriorityLevel { High = <any>'High', Normal = <any>'Normal', Low = <any>'Low'} In the HTML section, I have the following code: <b ...

What is the best way to reload a React/TypeScript page after submitting a POST request?

I am working on a custom plugin for Backstage that interacts with Argo CD via API calls. To retrieve application information, I make a GET request to the following endpoint: https://argocd.acme.com/api/v1/applications/${app-name} If the synchronizati ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...

When building with Angular using the "ng build" command, the JavaScript file names are altered

I'm currently learning Angular and I've noticed that when creating a new project with Angular CLI, files like runtime.js, polyfills.js, main.js, styles.css are generated. However, after running the ng build command, similar files can be found in ...

Accessing an external API through a tRPC endpoint (tRPC Promise is resolved before processing is complete)

I want to utilize OpenAI's API within my Next.js + tRPC application. It appears that my front-end is proceeding without waiting for the back-end to finish the API request, resulting in an error due to the response still being undefined. Below is my e ...

Issues with Typescript function overloads when dealing with union types

I'm struggling to make function overloads work properly in TypeScript. My challenge involves a basic union type and a function that is capable of handling either type. I have defined overloads to deal with them separately. type A = { type: "a", x: n ...

The tab title will be invisible if it is located within the second Angular component

Currently, I am utilizing the material css framework in combination with Angular (both latest versions). Everything works perfectly fine when I create tabs within one component. However, when I decide to make each tab a separate component, an issue arises ...

`What specific type should be assigned to the custom styled input component in MUI?`

Hey team! Would you mind helping me out with this issue? The Mui documentation suggests setting a type for a Mui Styled component like this: const MyComponent = styled(MuiComponent)(({ theme }) => ({ // styling })) as typeof MuiComponent This method ...

When using TypeScript, a custom property name within a type declaration must explicitly point to a predefined symbol

An error has occurred in ...component.ts (..,..): A computed property name in a type literal must directly refer to a built-in symbol. Error message: Cannot find name 'any'. I am seeking an object that contains strings that have another stri ...

adjusting state with React hooks

I currently have two buttons labeled create signature and Create delivery in my file PageOne.tsx. When the state is set to InDelivery, both buttons are visible. My goal is to hide the Create delivery button initially. However, when a user clicks on the cr ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

Incorporating a skeletal design effect into a table featuring sorting and pagination options

Is there a way to implement the Skeleton effect in a MUI table that only requires sorting and pagination functionalities? I tried using the 'loading' hook with fake data fetching and a 3-second delay, but it doesn't seem to work with DataGri ...