Reputation: 268
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
Upvotes: 0
Views: 107
Reputation: 513
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;
}
Upvotes: 0
Reputation: 39482
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.
Upvotes: 1