Angular 2 TypeScript how to find element in Array

前端 未结 7 794
抹茶落季
抹茶落季 2021-01-29 21:35

I have a Component and a Service:

Component:

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-29 21:53

    Transform the data structure to a map if you frequently use this search

    mapPersons: Map;
    
    // 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);
    }
    

提交回复
热议问题