【问题标题】:How do I keep only records that have letters in javascript?如何仅保留在 javascript 中包含字母的记录?
【发布时间】:2019-12-24 03:57:31
【问题描述】:

我有一个要验证的数组,特别是联系人列表中的姓名。此数组中的某些对象缺少名称,而在该属性中具有电话号码。如何过滤掉 name 属性不是由字母组成的任何记录? (名字只有字母)。因此,在下面的示例中,我应该只留下一条记录(Carl Johnson),因为该记录具有全名。

我的数据

let arrayIn=  [
    {phoneNumbers:[
        { label: 'work',  number: '+3476859087'},
        { label: 'mobile', number: '+4567893214'}
        ],
        lookupKey:"12345",
        company:"PHONE",firstName:"",contactType:"person",name:"71892823",id:"879",
        emails:[
            {email:'johnSmith@gmail.com'}
        ],
        lastName:"Smith",
    },
    {phoneNumbers:[
        { label: 'mobile', number: '+3476859087'},
        { label: 'work', number: '+4567773214'}
        ],
        lookupKey:"890744",
        company:"PHONE",firstName:"Carl",name:"Carl Johnson",id:"879",
        emails:[
            {email:'cjohnsonh@gmail.com'}
        ],
        lastName:"",
    }
    ]

fetchContacts = async () => {
  console.log('fetching contacts')
    let { status } = await Permissions.getAsync(Permissions.CONTACTS);
    if (status !== Permissions.PermissionStatus.GRANTED) {
      // TODO: Handle permissions denied.
      console.log('permissions have been denied')
      await Permissions.askAsync(Permissions.CONTACTS);
    } else {
      console.log('permission granted')

      //pull data from contacts          
      //const { data } = await Contacts.getContactsAsync({
      //fields: [Contacts.Fields.Emails],
      //});

      const { data } = await getContactsAsync({
        fields: [EMAILS, PHONE_NUMBERS],
      });

      if (data.length > 0) {
        const contact = data.reduce((acc, {
          id,
          name,
          phoneNumbers,
          emails
          }) => {
            return [...acc, {
              'id': name,
              'name': name ? name : null,
              'phone': phoneNumbers ?  this.validatePhone(phoneNumbers[0]['number']) : null,
              'email': emails ?  emails[0].email : null
              }];
          }, []);
        this.setState({ contacts: contact.slice(10,15).filter(c=>c.name!=(HERE IS WHERE I WOULD FILTER OUT ANY NAMES THAT HAVE NUMBERS)) })

      }
    }
};

【问题讨论】:

  • 一个更简单的方法是检查名称是否不是由数字组成的。
  • 我可能错误地表达了这个问题。这就是我的意思,我如何检查名称中是否有数字并因此将其过滤掉?
  • 我已经在下面发布了答案▼

标签: javascript arrays react-native


【解决方案1】:

更简单的方法是检查名称是否不是由数字组成的。您可以使用!Number()isNaN() 以及.filter() 来过滤name 是否为数字。

let arrayIn=  [
    {
     phoneNumbers:[
            { label: 'work',  number: '+3476859087'},
            { label: 'mobile', number: '+4567893214'}
        ],
     lookupKey:"12345",
     company:"PHONE",
     firstName:"",
     contactType:"person",
     name:"71892823",
     id:"879",
     emails:[
         {email:'johnSmith@gmail.com'}
     ],
     lastName:"Smith",
    },
    {
     phoneNumbers:[
        { label: 'mobile', number: '+3476859087'},
        { label: 'work', number: '+4567773214'}
     ],
     lookupKey:"890744",
     company:"PHONE",
     firstName:"Carl",
     name:"Carl Johnson",
     id:"879",
     emails:[
       {email:'cjohnsonh@gmail.com'}
     ],
     lastName:"",
    }
];
let arrayOut = arrayIn.filter(val => !Number(val.name));

console.log(arrayOut);

【讨论】:

    【解决方案2】:

    假设名称在包含数字时无效,您可以使用正则表达式在字符串中查找数字。

    const contacts = [
        {
            name:"71892823"
        },
        {
            name:"CarlJohnson"
        },
        {
            name:"Carl Johnson"
        },
        {
            name:"Carl124"
        },
        {
            name:"Carl124 Johnson"
        }
    ];
    
    const res = contacts.filter(person => !(/\d/.test(person.name)))
    
    console.log(res)
    

    输出

    [ { name: 'CarlJohnson' }, { name: 'Carl Johnson' } ]
    

    【讨论】:

      【解决方案3】:

      使用isNaN()filter() 函数:

      const contacts = [{phoneNumbers:[{label:'work',number:'+3476859087'},{label:'mobile',number:'+4567893214'}],lookupKey:"12345",company:"PHONE",firstName:"",contactType:"person",name:"71892823",id:"879",emails:[{email:'johnSmith@gmail.com'}],lastName:"Smith",},{phoneNumbers:[{label:'mobile',number:'+3476859087'},{label:'work',number:'+4567773214'}],lookupKey:"890744",company:"PHONE",firstName:"Carl",name:"CarlJohnson",id:"879",emails:[{email:'cjohnsonh@gmail.com'}],lastName:"",}]
      
      const res = contacts.filter(person => isNaN(person.name))
      
      console.log(res[0].name)
      console.log(res)

      【讨论】:

        【解决方案4】:

        您可以只使用match 函数,它会搜索给定字符串的匹配项。如果找到任何匹配项,它将返回一个包含所有匹配项的数组,否则将返回null

        filter(c => !c.name.match(/[0-9]/gi))
        

        【讨论】:

          【解决方案5】:

          你可以用 RegEx 完成它

          var data = [
              {phoneNumbers:[
                  { label: 'work',  number: '+3476859087'},
                  { label: 'mobile', number: '+4567893214'}
                  ],
                  lookupKey:"12345",
                  company:"PHONE",firstName:"",contactType:"person",name:"71892823",id:"879",
                  emails:[
                      {email:'johnSmith@gmail.com'}
                  ],
                  lastName:"Smith",
              },
              {phoneNumbers:[
                  { label: 'mobile', number: '+3476859087'},
                  { label: 'work', number: '+4567773214'}
                  ],
                  lookupKey:"890744",
                  company:"PHONE",firstName:"Carl",name:"Carl Johnson",id:"879",
                  emails:[
                      {email:'cjohnsonh@gmail.com'}
                  ],
                  lastName:"",
              }
              ];
              
              console.log(data.filter((data)=>!(/\d/.test(data.name))))

          【讨论】:

            猜你喜欢
            • 2014-06-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-06
            • 1970-01-01
            • 2020-06-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多