Reputation:
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?
Upvotes: 1
Views: 552
Reputation: 159
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"];
}
Upvotes: 0
Reputation: 57050
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];
Upvotes: 2