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

14,996

Solution 1

Yes, use the NSArray -valueForKey: method.

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

Solution 2

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);
Share:
14,996
QuangDT
Author by

QuangDT

Updated on June 05, 2022

Comments

  • QuangDT
    QuangDT almost 2 years

    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?

  • Itai Spector
    Itai Spector over 7 years
    @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! :)
  • nr5
    nr5 almost 7 years
    Can we do this for a set of keys, or is it available for only one key?
  • Mathi Arasan
    Mathi Arasan over 6 years
    This kind of method available in Swift?
  • David Gelhar
    David Gelhar over 6 years
    @user3589771 check out this question stackoverflow.com/questions/26367261/… for some possible solutions in Swift
  • Mathi Arasan
    Mathi Arasan over 6 years
    Thanks, I saw that, Accepted answer not works for me. Finally, I used this answer. I tried if swift provide single line like obj-c.