RunLoop
RunLoop

Reputation: 20376

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

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 without enumeration?

Upvotes: 12

Views: 15402

Answers (2)

Rob Keniger
Rob Keniger

Reputation: 46020

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);

Upvotes: 12

David Gelhar
David Gelhar

Reputation: 27900

Yes, use the NSArray -valueForKey: method.

NSArray *extracted = [sourceArray valueForKey:@"a key"];

Upvotes: 40

Related Questions