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

Encountered Angular SSR Serve Error: NullInjectorError - StaticInjectorError in AppServerModule with the following reference:

While working on building an application with Angular's SSR and serving it, I encountered a specific error. All services and components have been properly injected. Error: ERROR Error [NullInjectorError]: StaticInjectorError(AppServerModule)[REQUEST] ...

NextJS: Error - Unable to locate module 'fs'

Attempting to load Markdown files stored in the /legal directory, I am utilizing this code. Since loading these files requires server-side processing, I have implemented getStaticProps. Based on my research, this is where I should be able to utilize fs. Ho ...

Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on Gi ...

Issue with dynamic HTML preventing Bootstrap tooltip functionality

There's an HTML page where a section is dynamically generated through HTML injection from a typescript angularjs controller using $sce and ng-bind-html. The issue is that the custom bootstrap tooltip style doesn't seem to be applied, and only t ...

Retrieve a specific number from an equation

With my limited knowledge of TypeScript, I am attempting to extract a specific number from an expression. The goal is to locate and retrieve the digit from the following expression. ID:jv.link.weight:234231 In the given string, I aim to extract the numb ...

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

Retrieve the attribute from the element that is in the active state

I'm facing a challenge in determining the active status of an element attribute. I attempted the following approach, but it incorrectly returned false even though the element had the attribute in an active state - (.c-banner.active is present) During ...

What is the process for inputting a predefined function into an interface?

In my project, I have a Locale interface that defines the properties of a locale for my component: interface Locale { src: string; alt: string; language: string; i18nFormat: string; } During debugging, I am using the built-in .toSource() function ...

Send a Date Object through an Event Emitter to be used in a Date Picker

I created a personalized Date Picker Child Component, and when the onDateChange event occurs, I intend to send an event to the parent component. @Output() selectedDateChange = new EventEmitter<Date>(); onDateChange($event) { this.selectedDateCha ...

How should we correctly import jquery.inputmask?

Struggling to import jquery.inputmask using webpack and TypeScript? Head over to this discussion at Issue #1115 : Here's how I configured things with jqlite: To import in your app, use the following code: import InputMask from 'inputmask&apos ...

Steps for setting up Angular 5 on your system

My current project requires Angular 5, but with the recent release of Angular 7, I'm unsure how to set up Angular 5 on my computer. I had transitioned from Angular 6 a few months ago. Do I need to uninstall the latest version to work with Angular 5? ...

Offering a limited selection of generic type options in TypeScript

Is there a shorthand in TypeScript for specifying only some optional types for generic types? For example, let's say I have a class with optional types: class GenericClass<A extends Type1 = Type1, B extends Type2 = Type2, C extends Type3 = Type3> ...

Is there a way to retrieve all properties within a Typescript Class that includes optional properties?

If we have a scenario where: class ExampleType { item1?: string, item2?: string } and all the properties are OPTIONAL. Is there a way to generate an array of property names like: ["item1", "item2"] I attempted to use console.log( ...

JSON.stringify function provides detailed information about the indexes and length of an array

When using AJAX to send an array to my controller, I find it convenient to convert it to JSON format. This is how I construct my array: $("#selectedDropdown option").each(function () { selectedLanguages.push($(this).val()); }); To stringify it, I ...

When there is data present in tsconfig.json, Visual Studio Code does not display errors inline for TypeScript

After creating an empty .tsconfig file (consisting solely of "{ }"), Visual Studio Code immediately displays errors both inline and in the "problems" section. Interestingly, when I populate the tsconfig.json file with data, these errors disappear. Is there ...

`How to cleverly fake dependencies with symbols in Jest, Vue3, and Typescript?`

I am faced with the following scenario: // symbols.ts - Injection Key defined as a Symbol export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService'); // main.ts - globally provides a service using the injection key app.provi ...

Tips for showcasing an array in nested elements within an Angular mat-tree

I'm new to Angular and I need help displaying an array's values within the child elements of a material tree. Specifically, I want to show the names of fruits (such as Apple, Banana...) in the child elements. The colors and discounts from the ar ...

Using a custom jQuery function within an Angular component class

I have a custom query function that I wrote in a JavaScript file located under the source folder (/src/assets/inlineedit.js) of my Angular application. Here is the content of the file: $.fn.inlineEdit = function(replaceWith, connectWith) { $(this).ho ...