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

I have a Component and a Service:

Component:

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

Service:

_x000D_
_x000D_
@Injectable()_x000D_
export class PersonService {_x000D_
      getPersons(){_x000D_
        var persons: Person[] = [_x000D_
            {id: 1, firstName:'Hans', lastName:'Mustermann', email: '[email protected]', company:'Test', country:'DE'},_x000D_
            {id: 2, firstName:'Muster', lastName:'Mustermann', email: '[email protected]', company:'test', country:'DE'},_x000D_
            {id:3, firstName:'Thomas', lastName:'Mustermann', email: '[email protected]', company:'test', country:'DE'}_x000D_
        ];_x000D_
          _x000D_
        return persons;_x000D_
      }_x000D_
}
_x000D_
_x000D_
_x000D_

I want to get the Person Item with the Id ('personID'). The personID i get from Routeparam. For that I need the foreach loop? But I haven´t found a solution for this.

This question is related to angular typescript angular2-services

The answer is


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

Use this code in your service:

return this.getReports(accessToken)
        .then(reports => reports.filter(report => report.id === id)[0]);

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

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


Try this

          let val = this.SurveysList.filter(xi => {
        if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
          return xi.Description;
      })

      console.log('Description : ', val );

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


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular2-services

Getting Image from API in Angular 4/5+? How I add Headers to http.get or http.post in Typescript and angular 2? Angular 2 TypeScript how to find element in Array How do I create a singleton service in Angular 2? What is the proper use of an EventEmitter? Angular2: How to load data before rendering the component?