首页 > 解决方案 > 过滤认为具有辅助号码的联系人

问题描述

我试图过滤并仅获取该号码在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

标签: javascriptreact-native

解决方案


这应该适合你:

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)


推荐阅读