Discovering an element in an Array using Angular 2 and TypeScript

In my setup, I have a Component and a Service:

Component:

export class WebUserProfileViewComponent {
    persons: Person [];
    personId: number;
    constructor( params: RouteParams, private personService: PersonService) {
          
        
           this.personId = params.get('id');
           this.persons =  this. personService.getPersons();
           console.log(this.personId);  
        }
}

Service:

@Injectable()
export class PersonService {
      getPersons(){
        var persons: Person[] = [
            {id: 1, firstName:'Hans', lastName:'Mustermann', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c01191f18091e010d02022c18...},
            {id: 2, firstName:'Muster', lastName:'Mustermann', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb6ae...},
            {id:3, firstName:'Thomas', lastName:'Mustermann', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b465e585f4...}
        ];
          
        return persons;
      }
}

I am currently trying to retrieve the Person item based on the ID ('personID'), which I obtain from Routeparams. I am considering using a foreach loop, but I have not been able to find the right solution yet.

Answer №1

To extract specific data from an array in JavaScript, you can utilize either Array.filter method:

this.persons = this.personService.getPersons().filter(x => x.id == this.personId)[0];

or the Array.find method:

this.persons = this.personService.getPersons().find(x => x.id == this.personId);

Answer №2

Let's consider the following array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we aim to retrieve the item with Id = 1 and Name = "oily skin", we can use the following approach:

var skinName = skins.find(x=>x.Id == "1").Name;

The output will display the skinName as "Oily skin".

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

Answer №3

If you want to efficiently locate an object in an array based on one of its properties, you can utilize the combination of the .find method, arrow functions, and destructuring. Explore this code snippet taken from the helpful resource at MDN: MDN - Find an object in an array by one of its properties.

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

Answer №4

To optimize the search process, consider converting the data structure into a map

personMap: Map<number, Person>;

// initialize the map - run once or when there are changes in the person array
populatePersonMap() : void {
    this.personMap = new Map();
    for (let individual of this.personService.getPersons()) this.personMap.set(individual.id, individual);
}
retrievePerson(id: number) : Person {
    return this.personMap.get(id);
}

Answer №6

To integrate this functionality, simply insert the following code snippet into your application:

fetchReports(accessToken)
        .then(reports => reports.filter(report => report.id === id)[0]);

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

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

Angular5 routing causing issues with component rendering

In my application built with Angular 5, this is how my app.module.ts file looks like. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angu ...

Struggling with testing the checkbox when it changes inside the CardHeader Avatar={} component

I've recently implemented a feature similar to the example showcased on MaterialUI's TransferList. However, I'm encountering difficulties accessing a checkbox within the avatar={}. The project utilizes Jest and Enzyme for testing purposes. T ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Conduct surveillance on the service function call within the constructor

I am currently facing a challenge with trying to monitor a service function call that is executed in the constructor. The test is straightforward, simply aiming to confirm that the function call is indeed made. beforeEach(async(() => { TestBed.con ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Angular is flagging the term 'Component' as defined but not utilized within the codebase

Our Angular framework was recently upgraded to version 14 along with all dependent packages to their latest versions. However, post-update, an eslint error is popping up stating that the 'Component' import is defined but never used (unused-import ...

Using Angular's NgFor directive to loop through a list of items and trigger a click event

Is it possible to programmatically trigger a click event on a specific item within an ngFor loop? <ul> <li class="list" *ngFor="let ver of versions; (click)="versionView()">{{ver.name}}</li> </ul> ...

The method getManyAndCount() in TypeORM does not include related data in its return result

I'm completely new to TypeORM and NestJs. Currently, I am working on a project where I have an entity called VehicleModel which has a ManyToOne relationship with VehicleBrand. However, when I execute getManyAndCount() on my query, I am puzzled as to ...

Angular Date format

When I retrieve a date value from my angular interface, it appears in the following format. Sat Dec 29 2018 08:42:06 GMT+0400 (Gulf Standard Time) However, when I receive the data from an API, the JSON result looks like this. How can I make it the same t ...

Trouble displaying JSON markers on Ionic Google Maps

Looking for assistance related to this issue? Check out Ionic Google Maps Markers from JSON In my Ionic App with Google Maps integration, I'm facing an issue where although the map displays correctly, the pin markers are not showing up. It seems like ...

Utilizing lazy loading in conjunction with ngFor to optimize performance

I encountered the error Can't bind to 'ngForOf' since it isn't a known property of 'li'. Despite trying the suggested solutions, such as importing BrowserModule in the main module (app.module.ts) and importing CommonModule in ...

Error encountered while retrieving the cropped image, atob function was unable to execute

I am currently facing an issue with saving a cropped image in Chrome. When I try to save it, the download fails when using the Download button that I added to the page. I have successfully used ngx-image-cropper for cropping the image as intended. The cro ...

RxJs Subject: Acquiring the Sender

I have been working with Subjects and there is a .subscribe() in a specific class. Emitting values to this class from different other classes has resulted in the subscribe function being triggered multiple times, yet I am unsure of where these emits are co ...

Sharing a FormGroup between different components

For my Angular 2+ application utilizing reactive forms, I have a requirement to share the main FormGroup across multiple components. This will allow different sections of the form such as header and footer to be managed independently by separate components ...

What could be causing my Angular 7 project to have an overwhelming 40000 packages? Any tips on how to efficiently eliminate unnecessary dependencies?

Upon running npm audit in my terminal, the output displays: [...] found 0 vulnerabilities in 40256 scanned packages I'm puzzled by the fact that my project contains over 40,000 packages. This number seems excessive as I haven't intentionally ad ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

The function __WEBPACK_IMPORTED_MODULE_3_ionic_native__.a.open is returning an error

Is there a way to troubleshoot and resolve the following error: WEBPACK_IMPORTED_MODULE_3_ionic_native.a.open is not a function while utilizing the NishanthKabra/Ionic2_GoogleCalendar solution. I am interested in integrating Google Calendar into my Io ...

Angular 4: How to Format Date Input Types

When using the item edit option, I encountered a form with a specific date format. How can I modify the date format to display as dd/MM/yy instead of the full year? For example, I want it to show 07/07/18 but currently it is displaying the full year. Wha ...

Angular 6 is throwing an error message stating that it cannot access the 'image' property of an undefined object

Having trouble retrieving the details, as it is rendering to the dom with an undefined error. Check out this image for reference: https://i.sstatic.net/YB2Lf.jpg Welcome to the Book Details Component export class BookDetailsComponent implements OnInit { ...