Angular 2 TypeScript how to find element in Array Angular 2 TypeScript how to find element in Array angular angular

Angular 2 TypeScript how to find element in Array


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);


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


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 }