Search code examples
iosobjective-cnsarraynsdictionary

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

Solution

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