Reputation: 2283
If you have an array of dictionaries, how do I create a new array containing all the keys present for each dictionary in the array ?
NSArray *array = @[@{@"key1" : @"value 1"},
@{@"key2" : @"value 2"},
@{@"key3" : @"value 3"} ];
// how to achieve this?
NSArray *allKeys = @{@"key1", @"key2", @"key3"};
Upvotes: 0
Views: 1392
Reputation: 100622
Although Objective-C lacks an array-flattening method, you can nevertheless simplify the outer step:
NSMutableArray *result = [[NSMutableArray alloc] init];
for(NSArray *keys in [array valueForKey:@"allKeys"])
[result addObjectsFromArray:keys];
return [result copy];
Or, if you need keys deduplicated:
NSMutableSet *result = [[NSMutableSet alloc] init];
for(NSArray *keys in [array valueForKey:@"allKeys"])
[result unionSet:[NSSet setWithArray:keys]];
return [result allObjects];
... the only type assumption being (only slightly looser than) that array
is all dictionaries. If you can annotate the collections any further then I recommend that you do.
Upvotes: 1
Reputation: 246
plz use this code, I think it helps you
NSArray *array = @[@{@"key1" : @"value 1"},
@{@"key2" : @"value 2"},
@{@"key3" : @"value 3"} ];
NSMutableArray *key_array=[NSMutableArray array];
for (NSDictionary *dictionary in array) {
NSArray *key_dictionary=[dictionary allKeys];
for (NSString *string_key in key_dictionary) {
[key_array addObject:string_key];
}
}
NSLog(@"%@",key_array);
Upvotes: 1
Reputation: 42449
If you know that each element in the array is an NSDictionary
, you can call the allKeys
method on each item in the array. I've added a type check to this example in case your array contains other objects that are not NSDictionary
:
NSArray *array = @[@{@"key1" : @"value 1"},
@{@"key2" : @"value 2"},
@{@"key3" : @"value 3"}];
NSMutableArray *allKeys = [@[] mutableCopy];
for (id obj in array) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = obj;
[allKeys addObjectsFromArray:[dict allKeys]];
}
}
NSLog(@"%@", allKeys);
Logs:
2016-04-20 11:38:42.096 ObjC-Workspace[10684:728578] (
key1,
key2,
key3
)
And if you need an immutable NSArray
instead of an NSMutableArray
:
NSArray *allKeysImmutable = [allKeys copy];
Upvotes: 2