简体   繁体   中英

Given an array of NSDictionary object how to get all the keys?

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"};

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];

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM