Angular 2 TypeScript how to find element in Array

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

I have a Component and a Service:

Component:

相关标签:
7条回答
  • 2021-01-29 21:41

    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);
    
    0 讨论(0)
  • 2021-01-29 21:49

    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".

    0 讨论(0)
  • 2021-01-29 21:49

    Use this code in your service:

    return this.getReports(accessToken)
            .then(reports => reports.filter(report => report.id === id)[0]);
    
    0 讨论(0)
  • 2021-01-29 21:53

    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);
    }
    
    0 讨论(0)
  • 2021-01-29 21:55

    Try this

              let val = this.SurveysList.filter(xi => {
            if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
              return xi.Description;
          })
    
          console.log('Description : ', val );
    
    0 讨论(0)
  • 2021-01-29 22:00

    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 }
    
    0 讨论(0)
提交回复
热议问题