如何根据Ionic2中的id过滤数组元素?

时间:2017-08-18 07:55:41

标签: angular typescript ionic2

我正在使用Ionic2开发移动应用程序。目的是在主页中动态插入人员。每当我们点击一​​个人时,就会显示一个仅与该人(具有ID)相关的动态添加项目列表。我无法过滤每个人的项目,如何仅将项目过滤到特定的人员ID?

这是我添加新人条目的地方:

  public people:{personName:string, personID:string}[] = [];

  //will load all the people in the array
  ionViewWillEnter(){
    //addPersons is constructed from addPersonsService
    this.people = this.addPersons.getPeople();
  }

  //from the HTML, it will parse the personID from the array
  //it will redirect to the list of items for the specific person
  viewDebts(personID:string){  

    this.navCtrl.push(DebtsListPage, personID);

  }

这是addPersonsService

public people: {personName:string, personID:string}[] = [];

//this is called upon click from the HTML
addPerson(person:{personName:string, personID:string}  ){
    this.people.push(person);
}

getPeople(){   
    return this.people.slice();
}

generateID(id:string){
    return id;

}

在这里,我正在显示每个人的项目

  debtValue:{personDebt:string, personId:string}[] = [];

  //this is where the list of items will be displayed
  ionViewWillEnter(){
    var id = this.navParams; //getting the id from the previous page
    this.debtValue = this.debts.getPersonsDebt(id); //debts comes from DisplayDebtsService
  } 

  //adding the item
  addDebts(debt:{personDebt:string, personId:string}) {
    this.debts.addDebt(debt);

  }

最后这是DisplayDebtsService

  public debt:{personDebt:string, personId:string}[] = [];


  addDebt(debt:{personDebt:string, personId:string}){
      this.debt.push(debt);
  }

  getPersonsDebt(id:any){
      //this is where I am struggling. How do I filter the results based on the id of the person?
        return this.debt;
  }

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您是否只是尝试使用.find()? ..或.filter() ..

但在这里我认为find()更好,因为你过滤ID ...它看起来像一个PK键..所以你只面对一个人从你的方法返回而不是更多(如filter()做)

类似的东西:

getPersonsDebt(id:any){
      //this is where I am struggling. How do I filter the results based on the id of the person?
        return this.debt.find(p=> p.id === id);
  }

希望它可以帮到你