user4151918
user4151918

Reputation:

Is there a better way to flatten an NSArray of NSDictionaries?

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

Answers (2)

Jaycee
Jaycee

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

Léo Natan
Léo Natan

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

Related Questions