Ios NSDictionary array - grouping values and keys

天涯浪子 提交于 2019-12-06 01:39:40

You could create an NSMutableDictionary and loop through your array, adding the keys to the mutable dictionary using the allKeys.

For example, if your array was called dictArray, you could do:

NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
    NSArray *keys = [currentDictionary allKeys];
    for (int n=0;n<[keys count];n++) {
        NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
        if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
        [dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
        [combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
    }
}

This code first creates a dictionary combinedDictionary that will be your final dictionary. It loops through all of the dictionaries in your array and for each one does the following:

First, it gets an array of all keys in the dictionary. For the dictionaries you provided this array will look like @[@"Bath"] for the first 3 and @[@"Birmingam"] for the other two.

The code then loops through these keys and gets the already existing dictionary from the combined dictionary from this key. If the dictionary doesn't exist, one is created.

Then, it adds all of the values from the dictionary from the array and sets the new dictionary to be the one in combinedDictionary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!