我试图过滤并仅获取numbers
中该号码的联系人,我的问题是一个号码可能是该联系人的次要号码,而filter(indexOf(foreach()))
在这里似乎不起作用建议?
const filteredContacts = contacts.filter(contact => numbers.indexOf(contact.phoneNumbers.forEach(phone => phone.number)) > -1);
//sample of contacts
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
//Sample of numbers
numbers = [
(707) 555-1854,
555-610-6679
]
//Expected
filteredContacts = //Both contacts
答案 0 :(得分:1)
这应该对您有用:
const contacts= [
{
company: "Financial Services Inc.",
// ....
phoneNumbers:[
{
//...
number: "(555) 766-4823",
},
{
//...
number: "555-610-6679",
}
]
}
//...
];
//Sample of numbers
const numbers = [
'(707) 555-1854',
'555-610-6679'
]
const filteredContacts = contacts.filter(contact => {
let number_exists=false;
contact.phoneNumbers.map(phone => phone.number).forEach( phoneNr =>{
if(numbers.indexOf(phoneNr)>-1) number_exists=true;
}
);
return number_exists;
}
);
//Expected
console.log(filteredContacts)