Iterar over array of entity and get value of some key based on value of “other key” matche

前端 未结 2 1755
鱼传尺愫
鱼传尺愫 2021-01-22 03:47

I have an array of entity class (eg SubmittedAnswer). Its JSON format is look like as below.


{
\"submittedAnswers\": [{
    \"submittedQuestionId\": \"C7B3         


        
相关标签:
2条回答
  • 2021-01-22 04:09

    Assuming that submittedAnswers is an NSArray of NSDictionary objects, I found the answer here: Stack Overflow > iPhone - Searching NSArray of NSDictionary objects

    // Array `submittedAnswers` of sample data
    NSArray* submittedAnswers = @[
    @{
    @"submittedQuestionId" : @"C7B3C4BE-CC3C-438F-A118-E798884A5FE0" ,
    @"serialNumber" : @4 ,
    @"option" : @" it has a very large mass." ,
    @"testQuestionId" : @"55230160-b905-47d5-a91c-e1dda6dd0634" } ,
    @{
    @"submittedQuestionId" : @"9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0" ,
    @"serialNumber" : @1 ,
    @"option" : @" downward" ,
    @"testQuestionId" : @"fd0b3ae0-e999-48a6-89b8-a89b02e7b793" } ] ;
    
    
    NSString *submittedQuestionId = @"9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0" ;
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"submittedQuestionId = %@", submittedQuestionId] ;
    NSArray* foundQuestions = [submittedAnswers filteredArrayUsingPredicate:predicate] ;
    NSDictionary* foundQuestion = foundQuestions[0] ;
    
    0 讨论(0)
  • 2021-01-22 04:16
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"submittedQuestionId == %@", yourSubmittedQuestionId];
    NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
    id firstFoundObject = nil;
    if ([filteredArray count] > 0) {
        firstFoundObject = [filteredArray objectAtIndex:0];
    }
    

    Please make sure your SubmittedAnswer class has property submittedQuestionId

    0 讨论(0)
提交回复
热议问题