NSPredicate for inner key in array of dictonary

2020-04-20 08:41发布

问题:

i have an array of dictionay in the following format

    [
 {
      "student": {
        "id": "1",

        "studentUserDetail": {
          "firstName": "Bonny",
          "lastName": "Roby"  
        }
    }

 },

 {
      "student": {
        "id": "1",

        "studentUserDetail": {
          "firstName": "Bonny",
          "lastName": "Kety"  
        }
    }

 },

 {
      "student": {
        "id": "1",

        "studentUserDetail": {
          "firstName": "Arther",
          "lastName": "Fone"  
        }
    }

 },

]

In the above array i need to filter all elements containing a serachKey (eg Bonny) in the inside key student.StudentUserDetails.firstName . How can i filter using NSPredicate

回答1:

NSString *name = @"Bonny";
NSPredicate *pred = [NSPredicate predicateWithFormat:
                    @"student.studentUserDetail.firstName == %@", name];     
NSArray *arr = [self.anArray filteredArrayUsingPredicate:pred];

NSLog(@"Bonny found at : %@", arr);

Edit:

If you want to search based on a pattern, then use:

NSPredicate *pred = [NSPredicate predicateWithFormat:
                    @"student.studentUserDetail.firstName beginswith[cd] %@", name];


回答2:

NSArray *array = @[
                  @{
                     @"student": @{
                             @"id": @"1",
                             @"studentUserDetail": @{
                                     @"firstName": @"Bonny",
                                     @"lastName": @"Roby"
                         }
                     }
                     },
                  @{@"student": @{
                            @"id": @"1",
                            @"studentUserDetail": @{
                                    @"firstName": @"Bonny",
                                    @"lastName": @"Kety"
                                }
                            }
                  },
                  @{
                     @"student": @{@"id": @"1",
                                   @"studentUserDetail": @{
                                           @"firstName": @"Arther",
                                           @"lastName": @"Fone"
                                           }
                                   }
                  }];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(student.studentUserDetail.firstName) == %@", @"Bonny"];
NSArray *newArray = [array filteredArrayUsingPredicate:predicate];


回答3:

NSPredicate *filter =  [NSPredicate predicateWithFormat:@"student.studentUserDetail.firstName CONTAINS[cd] %@ ", searchString];

worked perfectly for me