使用Angular-我有一个数组为people[]
的json文件,其中数组为phones[]
我想回来
people[index].phones[index].phonenumber
(where people.personid = x and people.phones.phoneid = y)
任何建议都将受到赞赏
答案 0 :(得分:1)
只需在数组上使用filter
函数。
let person = people.filter(person => person.personId === x);
let phone = person && person.phones.filter(phone => phone.phoneId === y);
以下是 Working Example as a Sample StackBlitz 供您参考。
答案 1 :(得分:0)
您可以使用过滤器函数来返回过滤后的数组
private filterPhone(x:number,y:number) : number {
let phoneNum : number;
let person = this.people.filter(person => person.personId === x);
let phone = person.length > 0 && person[0].phones.filter(phone => phone.phoneId === y);
if(phone.length > 0 && phone[0].phoneNumber){
phoneNum = phone[0].phoneNumber;
}
return phoneNum;
}
或者您可以使用findIndex()函数来实现此目的。
private findPhoneById(x:any,y:any) : number {
let result : number = -1;
let personIndx = this.people.findIndex(p => p.personId === x);
if(personIndx > result){
let phoneIndx = this.people[personIndx].phones.findIndex(phone => phone.phoneId === y);
if(phoneIndx > result){
result = this.people[personIndx].phones[phoneIndx].phoneNumber;
}
}
return result;
}