using Angular - I have a json file with an array people[], which has an array phones[]
I want to return
people[index].phones[index].phonenumber
(where people.personid = x and people.phones.phoneid = y)
Any suggestions are greatly appreciated
Simply use the filter function on the arrays.
let person = people.filter(person => person.personId === x);
let phone = person && person.phones.filter(phone => phone.phoneId === y);
Here's a Working Example as a Sample StackBlitz for your ref.
personId and phoneId which could be different from the indices of the Objects in the respective arrays.You can use a filter function which returns a filtered array
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;
}
Or you could use a findIndex() function for achieving this.
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;
}
peopleIdandphoneIdbe used asindiecesof the people array and phones array respectively? Or are both these arrays array of objects?