Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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: 'mustermann@test.com', company:'Test', country:'DE'},
{id: 2, firstName:'Muster', lastName:'Mustermann', email: 'mustermann@test.com', company:'test', country:'DE'},
{id:3, firstName:'Thomas', lastName:'Mustermann', email: 'mustermannt@tesrt.com', 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.
–
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);
–
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".
–
–
–
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 }
Transform the data structure to a map if you frequently use this search
mapPersons: Map<number, Person>;
// prepare the map - call once or when person array change
populateMap() : void {
this.mapPersons = new Map();
for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
getPerson(id: number) : Person {
return this.mapPersons.get(id);
from TypeScript you can use native JS array filter() method:
let filteredElements=array.filter(element => element.field == filterValue);
it returns an array with only matching elements from the original array (0, 1 or more)
Reference:
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.