Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice

I am developing an angular application that fetches data from an API and presents it on the page

The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls

apiservice.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';


@Injectable({
  providedIn: 'root'
})

export class ApiserviceService {

constructor(private _http:HttpClient) { }

getData(){

return this._http.get('APIURL');
}

}

Additionally, I have another component that observes this call and maps the data to an array

data.component.ts

import { Component, OnInit } from '@angular/core';
import { map, toArray } from 'rxjs';
import { ApiserviceService } from '../apiservice.service';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.scss']
})
export class VenueComponent implements OnInit {

  
  data: any = [];

  constructor(private service:ApiserviceService) {}

    MapData() {
        this.service.getData().subscribe(result=>{
        this.data=result;
        console.log(this.data);
})
  }


 ngOnInit() {
    this.MapData()
  }




}

The data is then displayed in a table

data.component.html

<table>
    <tr *ngFor= "let item of data | keyvalue" >
        <td>{{item.key}} : {{item.value}}</td>
</table>

Currently, I am using *ngFor to iterate through the array, but want to exclude certain keys/values from being displayed

For instance, I wish to show key2 and value2 but not key1 and value1

[Key1 : value1], [Key2 :value2]

Any suggestions on how to achieve this would be highly appreciated

Answer №1

From my point of view, there are at least two ways to approach this situation. The first option is to filter the observable data:

this.service.getData().pipe(
    filter(o => {
        return // your condition here
    })
).subscribe(result=>{

The second alternative is to develop a custom pipe. By creating a pipe that extends the keyvalue pipe and filters the data according to your requirements, you can achieve the desired outcome. Various tutorials are available that provide detailed instructions on how to create custom pipes.

Answer №2

I believe utilizing the Angular Slice Pipe would be beneficial for this situation.

<table>
    <tr *ngFor="let item of data | keyvalue | slice: 1">
        <td>{{item.key}} : {{item.value}}</td>
</table>

I hope this solution proves to be helpful. Thank you!

[1]: https://angular.io/api/common/SlicePipe

Answer №3

One important tip: always assign types to your variables. This helps you keep track of the data you're working with and makes it clearer for others to understand your goals.

My recommendation is to move this logic into a service for reusability. Additionally, consider using a reactive approach to avoid manual unsubscribing from requests. The code assumes that the API response is an array, not an object.

apiservice.service.ts

...
export class ApiserviceService {
  data$ = this._http.get('APIURL').pipe(
    map(data => data.filter(item => item.key !== 'Key1'))
  );

constructor(private _http:HttpClient) { }
...

data.component.ts

...
public data$ = this.service.data$;
...

data.component.html

<table>
    <tr *ngFor= "let item of data$ | async" >
        <td>{{item.key}}</td>...
</table>

In this case, I suggest avoiding pipes as they should be more generic and your filtering logic appears too specific for a pipe implementation.

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

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

The Reactjs infinite scroll feature continuously displays fresh data

Every time I scroll, my data is always rendering on page 2 and page 1 disappears, and the items.concat function is not working properly. My fetch data code looks like this: const FetchUrl = async (p) =>{ const Url = await fetch(`api-link=${p}`); ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

Guidelines for automatically exporting (and downloading) a Highcharts chart created in Angular

I've been working on an Angular project where I successfully created a chart using the Highcharts library and the Angular-Highcharts package. The chart looks great, but now I'm facing an issue with automatically exporting it using the Highcharts ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

When the typeof x is determined to be "string", it does not result in narrowing down to just a string, but rather to T & string

Could someone help me understand why type narrowing does not occur in this specific case, and return typing does not work without using: as NameOrId<T>; Is there a more efficient way to rewrite the given example? Here is the example for reference: ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

Restrict PHP JSON file to contain only up to 20 objects

I have a form that generates a JSON file when submitted. I am working on limiting the JSON file to contain only 20 objects, specifically to display the top 20 test scores. Each new score submitted should replace the lowest score out of the existing 20. It& ...

Experience the power of Stimulsoft reporting integrated with Angular and Asp.net Core-framework!

I've created a Webservice in Asp.net Core to generate reports which is then called in an Angular app to display the reports. However, when I try to show the report in Angular, it only shows a blank page. What could be causing this issue and how can I ...

What techniques can be employed to dynamically modify Typescript's AST and run it while utilizing ts-node?

Below is my approach in executing a TypeScript file: npx ts-node ./tinker.ts In the file, I am reading and analyzing the Abstract Syntax Tree (AST) of another file named sample.ts, which contains the following line: console.log(123) The goal is to modify ...

Describing the implementation of UNO out parameters within definitions

The UNO API offers support for inout and out parameters. In this scenario, a variable is passed into a function, the function modifies the variable, and the updated value of the variable can be accessed outside the function. Javascript lacks native suppor ...

What does the 'key' parameter represent in the s3.put_object() function?

Currently, I'm utilizing Boto in my project to upload artifacts to an s3 bucket. However, I am uncertain about the usage of the Key parameter within the put_object() method: client.put_object( Body=open(artefact, 'rb'), Bucket=buc ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

I'm having trouble viewing the unique Google Map design on my application

I have recently customized Google maps following the guidelines in this documentation: https://developers.google.com/maps/documentation/javascript/styling For styling, I utilized the Cloud tool and opted for the available template instead of using JSON st ...

Continue iterating using (forEach, map,...) until the object (children) has no more elements

I need to disable the active status for all elements within my object structure. Here is an example of my object: const obj = { name: 'obj1' , ative: true , children: [ { name: 'obj2' , ative: true , children: ...

Adding elements to an array using JavaScript

What is the correct way to add new values to an array like this? json = {"awesome":"45.22","supercool":"9876"} I attempted json.push("amazingness":"45.22");, but unfortunately it was not successful. ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

How to Retrieve the Value of <input type=date> Using TypeScript

I am currently developing a survey website and need assistance with retrieving user input for two specific dates: the start date and end date. I aim to make the survey accessible only between these dates, disabling the "take survey" button after the end da ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Struggling to retrieve data with arrow function in Vue

I'm currently learning Vue and facing an issue with fetching data from an API to my component. I have a service class that successfully retrieves data from the API, as the API itself is working fine. Here's the code snippet: import IReview from & ...