12

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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
RunLoop
  • 20,288
  • 21
  • 96
  • 151

2 Answers2

40

Yes, use the NSArray -valueForKey: method.

NSArray *extracted = [sourceArray valueForKey:@"a key"];
David Gelhar
  • 27,873
  • 3
  • 67
  • 84
  • @e.James, you learn if you ask and your curious. I came up with the thought about how to implement this, because i didn't want to loop around and do like the old-school style. I'm glad I looked for a way of doing that, and like you say, learnt another new thing, cheers for learning everyday! :) – Itai Spector Sep 15 '16 at 07:35
  • Can we do this for a set of keys, or is it available for only one key? – nr5 Jul 29 '17 at 18:57
  • This kind of method available in `Swift`? – Mathi Arasan Aug 09 '17 at 12:24
  • @user3589771 check out this question https://stackoverflow.com/questions/26367261/key-value-coding-kvc-with-array-dictionary-in-swift for some possible solutions in Swift – David Gelhar Aug 09 '17 at 15:18
  • Thanks, I saw that, [Accepted answer](https://stackoverflow.com/a/26367532/3589771) not works for me. Finally, I used [this answer](https://stackoverflow.com/a/30693198/3589771). I tried if swift provide single line like obj-c. – Mathi Arasan Aug 10 '17 at 11:39
12

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);
Rob Keniger
  • 45,830
  • 6
  • 101
  • 134