admin管理员组

文章数量:1399509

In my TypeScript I have this class:

export class PhoneBookPerson {
    Email: string;
    Name: string;
    Phonenumber: string;
    ProfileImg: string;
    Department: string;
    JobTitle: string;
    Username: string;
}

I'm wondering how can I check if any of the properties contains a specific value.

let $SearchTerm = target.val();
function RetrievedUsers(sender: any, args: any) {
    for (let i = 0; i < users.get_count(); i++) {
        let user = users.getItemAtIndex(i);

        let person = new PhoneBookPerson();
        person.Name = user.get_loginName();
        person.Email = user.get_email();
        person.Username = user.get_loginName();
        person.JobTitle = user.get_title();
        <-- search of person contains value from $SearchTerm                        
        usermatch.push(person);
    }
}

In my TypeScript I have this class:

export class PhoneBookPerson {
    Email: string;
    Name: string;
    Phonenumber: string;
    ProfileImg: string;
    Department: string;
    JobTitle: string;
    Username: string;
}

I'm wondering how can I check if any of the properties contains a specific value.

let $SearchTerm = target.val();
function RetrievedUsers(sender: any, args: any) {
    for (let i = 0; i < users.get_count(); i++) {
        let user = users.getItemAtIndex(i);

        let person = new PhoneBookPerson();
        person.Name = user.get_loginName();
        person.Email = user.get_email();
        person.Username = user.get_loginName();
        person.JobTitle = user.get_title();
        <-- search of person contains value from $SearchTerm                        
        usermatch.push(person);
    }
}
Share Improve this question edited May 5, 2017 at 9:24 mleko 12.3k7 gold badges52 silver badges71 bronze badges asked Jan 25, 2017 at 12:54 user7255640user7255640 7
  • Where is $SearchTerm variable? what value you want to match with wich attribute of Person? – Bhushan Kawadkar Commented Jan 25, 2017 at 12:56
  • $SearchTerm contains any kind of value form a user input. I would like it to see if any property in Person contains that value – user7255640 Commented Jan 25, 2017 at 12:58
  • Just use Object.keys(person).some(k => k.includes($SearchTerm)) – AlexG Commented Jan 25, 2017 at 13:10
  • I can not select includes – user7255640 Commented Jan 25, 2017 at 13:14
  • And why cant you "select includes"? – robkuz Commented Jan 25, 2017 at 13:19
 |  Show 2 more ments

1 Answer 1

Reset to default 4

Iterate over object properties and check if any of them contains specified text.

Sample function to do so (I assume only string properties in object)

function objectContains(obj, term: string): boolean {
  for (let key in obj){
    if (obj[key].indexOf(term) != -1) return true;
  }
  return false;
}

Example usage

if (objectContains(person, $SearchTerm)) {
  // do something
}

本文标签: javascriptCheck if Object contains string in TypeScriptStack Overflow