Retrieve objects from an array that contain a certain specified key

I am trying to extract the objects from All_reports that contain the key: comentarioAdmin. Currently, I am retrieving all reports from All_reports, but I only want the reports that have the key comentarioAdmin. Thank you!

getReports() {
    this.Service.getReportes().subscribe((data) => {
      this.All_reports = data;

      console.log('response of student->' + this.All_reports);
    });
  }

Here is how my array of objects looks like, some with comentarioAdmin and some without:

[
.
.
.

{
        "_id": "5ee1b1f04e9bfe060050cacf",
        "nombre": "Mario",
        "apellido": "López No-Gattelll",
        "correo": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6d6178676a3f374e696178206376">[email protected]</a>",
        "direccion": "Varsovia 54, Juárez, 06600 Cuauhtemoc, CDMX",
        "referencia": "",
        "tipoPersona": "Otro",
        "comentario": "Hay una fuga a la mitad de la calle.",
        "numeroReporte": 2,
        "__v": 0,
        "comentarioAdmin": "PRUEBA"
    },
    {
        "_id": "5ee1c247634773d6e00e44d4",
        "nombre": "Fabián",
        "apellido": "Oropeza Oropeza",
        "correo": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dfbfcfff2aff2ddfcf2f1b3fef2f0">[email protected]</a>",
        "direccion": "Calle 10 de febrero 56 MH, CDMX",
        "referencia": "Es mi casa",
        "tipoPersona": "Otro",
        "comentario": "Justo en rente de mi casa hay una fuga y mi carro se moja cuando salgo.",
        "numeroReporte": 1,
        "__v": 0,
    },
.
.
.
]

Answer №1

If you're looking to achieve this task using an array, you can utilize the filter() function. Here's a sample code snippet:

var input = [{
    "comentario": "There is a leak in the middle of the street.",
    "reportNumber": 2,
    "__v": 0,
    "adminComment": "TEST"
  },
  {
    "reference": "It's my house",
    "personType": "Other",
    "comentario": "Right in front of my house, there is a leak and my car gets wet when I leave.",
    "reportNumber": 1,
    "__v": 0,
  }
];


var output = input.filter(item => {
  if (item.adminComment) {
    return item;
  }
});

console.log(output);

Typescript:

getReports() {
  this.Service.getReportes().subscribe((data) => {
    this.All_reports = data.filter(item => {
      if (item.adminComment) {
        return item;
      }
    });
    console.log('student response->' + this.All_reports);
  });
}

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

angular proxy configuration malfunctioning

I'm struggling to figure out where my mistake is. Despite trying the solution provided in an answer, the issue persists. Here are a few related threads I've explored: Angular-CLI proxy to backend doesn't work Configure Angular-cli proxy f ...

Creating a Tailored Validation Function in Angular 6

Looking to develop a custom generic validator that accepts the regular expression pattern and the property name (from a formgroup) as parameters? Take a look at this code snippet: UserName: new FormControl('', [ Validators.require ...

Having trouble injecting $resource into my Jasmine unit test

I've encountered an issue while trying to test my self-written service that utilizes $resource. I'm facing difficulties when trying to inject $resource into my test spec. My setup includes Typescript with AngularJS 1.6.x, and here is a snippet o ...

How to disable the first option in an Angular 2 select dropdown

I'm working with a select component, and here is the code snippet I have: <select name="typeSelection" materialize="material_select" [(ngModel)]="trainingplan.type" > <option [ngValue] = "null" disabled selected>Please choose a ...

Adapting imports in Typescript for seamless npm distribution

Currently, I'm facing an issue with module resolution while compiling my NPM package written in Typescript for publishing. In my project, I've been using non-relative imports to avoid the hassle of excessive ../../../. However, according to TypeS ...

Issue Detected: The function this.route.params.flatMap is not recognized

Seeking guidance on transitioning to id, or a similar concept that's hard to articulate. Upon clicking a button to navigate to a specific user, encountering the following error: ERROR TypeError: this.route.params.flatMap is not a function at UserSho ...

Experimenting with Jest testing for a Component or Service that includes the use of "declare var" functionality

During the testing of my component or service, an error has occurred: ReferenceError: flagPath is not defined The variable flagPath is sourced from a configuration file named config.js within the assets folder. Is there a method to incorporate it into ...

Should the getDownloadURL() from Firebase Storage be regenerated every time, or can it be reused?

Should I store and reuse the URL received from angularfire2's getDownloadURL() in the database instead of calling getDownloadURL() every time I want to show an image from Firebase Storage? Whenever I use getDownloadURL() in my component, the images a ...

Learn how to securely download files from an Azure Storage Container using Reactjs

I'm currently working on applications using reactjs/typescript. My goal is to download files from azure storage v2, following a specific path. The path includes the container named 'enrichment' and several nested folders. My objective is to ...

Search through a group of distinct objects to find arrays nested within each object, then create a new object

I am currently working with objects that contain arrays that I need to filter. My goal is to filter an array of classes based on category and division, then return the new object(s) with the filtered arrays. Below is a representation of the JSON structure ...

After ngAfterViewInit, the @ViewChild element has not been defined

@ViewChild('videoPlayer') myVidElement: ElementRef; There is an HTML5 video element in the markup with the ViewChild specified as above However, I am facing an issue where the element is not accessible and is logged as undefined in both ngOnIni ...

Issue with TypeScript not detecting exported Firebase Cloud Functions

Dealing With Firebase Cloud Functions Organization I am managing a large number of Firebase Cloud Functions, and in order to keep the code well-structured, I have divided them into separate files for each function category (such as userFunctions, adminFun ...

Graphql is a revolutionary method for structuring entities in a hierarchical schema

Hey there! I'm fairly new to the world of GraphQL, and I've been curious about whether it's possible to organize entities into a tree schema similar to how Swagger handles it. I'm using Apollo Server for my UI/debugging of my GraphQL. ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Is there a way to transform Observable<Observable<Organization>[]> into Observable<Organization[]>?

I have implemented ngrx/store in my project. .map((p: Observable<Organization>[]) => { return new usersActions.GetOrganizationSuccess(p); }) The GetOrganizationSuccess action is designed to accept Organization[] as the payload. Is ...

Angular-6 Issue: Default Value Not Displaying in Drop-Down List

I am attempting to bind an array into a list. The binding part is functioning correctly, but the default value of the drop down is not displaying. Initially, the array does not contain any values. Here is the code snippet: <select (change)="select($ev ...

Infinite Loop Issue in Angular2 RC5 when using the templateUrl

Encountering an issue with Angular2 RC5 that seems to be causing an infinite loop problem. The app.component, which is bootstrapped by the app.module, appears quite simple: @Component({ selector: 'my-app', template: `TEST` }) export cl ...

Unexpected MySQL interactions when utilizing the C libmysqlclient

In my project, I have developed a processing engine in C that is responsible for extracting 40k records from a table, performing data processing on the extracted information, and then writing the results to a separate table. Initially, when I display the p ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

Tips on inserting a variable into an icon class in Angular 7

I am looking to add a unique icon to each item on my page, which is being generated inside of an *ngfor loop. For example: <i class="var"></i> Instead of 'var', I want to dynamically insert a variable provided by my service class in ...