1

I have an array of dictionaries, that look like this:

    @[@{@"object" : @"circle", @"total" : @12},
      @{@"object" : @"square", @"total" : @7},
      @{@"object" : @"triangle", @"total" : @4},
    ];

I want to flatten this to a dictionary, where the key is the object, and the value is the total:

    @{@"circle" : @12,
      @"square" : @7,
      @"triangle" : @4,
    };

Is there any way to do this, other than iterating through the array, and mapping the keys?

NSMutableDictionary *objects = [[NSMutableDictionary alloc] init];
for (NSDictionary *object in array)
{
    [objects setObject:object[@"total"] forKey:object[@"object"];
}

If there's no other way using Objective C, how would the transformation be written in Swift?

  • 1
    Swift 2 will allow you to apply a map function to a dictionary: http://stackoverflow.com/questions/24116271/whats-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift – Mark Jul 03 '15 at 17:49

2 Answers2

2

One way to do it is using KVC:

NSArray* array = @[@{@"object" : @"circle", @"total" : @12},
    @{@"object" : @"square", @"total" : @7},
    @{@"object" : @"triangle", @"total" : @4},
];
NSArray* objects = [array valueForKeyPath:@"object"];
NSArray* totals = [array valueForKeyPath:@"total"];
NSDictionary* final = [[NSDictionary alloc] initWithObjects:totals forKeys:objects];
Léo Natan
  • 56,823
  • 9
  • 150
  • 195
  • Or you could use 2 swift `filter` calls to get your objects and totals instead of using KVC, then combine them as you've done. – Duncan C Jul 03 '15 at 17:33
0

The transformation to swift would be as follows:

var array = [[String : String]](); // Let this be your array
var requiredDictionary = [String : String](); //be your required dictionary
for object in array {
    let key = object["object"]
    requiredDictionary[key!] = object["total"];
}
Jaycee
  • 159
  • 6