Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 TypeScript how to find element in Array

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: '[email protected]', company:'Test', country:'DE'},
            {id: 2, firstName:'Muster', lastName:'Mustermann', email: '[email protected]', company:'test', country:'DE'},
            {id:3, firstName:'Thomas', lastName:'Mustermann', email: '[email protected]', company:'test', country:'DE'}
        ];
          
        return persons;
      }
}

I want to get the Person item with the ID ('personID'). The personID I get from Routeparams. For that I need the foreach loop? But I haven't found a solution for this.

like image 694
trap Avatar asked Oct 02 '22 07:10

trap


People also ask

How do you check if an array contains an element in TypeScript?

Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise. Copied!


3 Answers

You need to use method Array.filter:

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

or Array.find

this.persons =  this.personService.getPersons().find(x => x.id == this.personId);
like image 308
Andrei Zhytkevich Avatar answered Oct 14 '22 00:10

Andrei Zhytkevich


Assume I have below array:

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

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

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

The result will return the skinName is "Oily skin".

enter image description here

like image 94
Hai Dinh Avatar answered Oct 14 '22 00:10

Hai Dinh


You could combine .find with arrow functions and destructuring. Take this example from MDN.

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 }
like image 12
Nathan Beck Avatar answered Oct 13 '22 23:10

Nathan Beck