From array of dictionaries, make array containing values of one key

前端 未结 2 674
一个人的身影
一个人的身影 2020-12-16 00:45

I have an array of dictionaries. I would like to extract an array with all the elements of one particular key of the dictionaries in the original array. Can this be done wit

相关标签:
2条回答
  • 2020-12-16 01:02

    Yes, use the NSArray -valueForKey: method.

    NSArray *extracted = [sourceArray valueForKey:@"a key"];
    
    0 讨论(0)
  • 2020-12-16 01:09

    Yes, just use Key-Value Coding to ask for the values of the key:

    NSArray* names = [NSArray arrayWithObjects:
                      [NSDictionary dictionaryWithObjectsAndKeys:
                       @"Joe",@"firstname",
                       @"Bloggs",@"surname",
                       nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:
                       @"Simon",@"firstname",
                       @"Templar",@"surname",
                       nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:
                       @"Amelia",@"firstname",
                       @"Pond",@"surname",
                       nil],
                      nil];
    
    //use KVC to get the names
    NSArray* firstNames = [names valueForKey:@"firstname"];
    
    NSLog(@"first names: %@",firstNames);
    
    0 讨论(0)
提交回复
热议问题