Search code examples
objective-clogicnsarraynsdictionary

Dictionary from an Array of Dictionary - Logical Challenge in Objective-C


The goal is converting Array of Dictionaries into one Dictionary of different objects. How can I do that?

I have an Array of records in this format,

originalArray = [{
        "valid": "Y",
        "mof": "ON",
        "dof": "17-05-2019",
        "rtntype": "CODE1",
        "ret_prd": "042019",
    },
    {
        "valid": "Y",
        "mof": "ON",
        "dof": "19-04-2019",
        "rtntype": "CODE1",
        "ret_prd": "032019",
    },
    {
        "valid": "Y",
        "mof": "ON",
        "dof": "19-04-2019",
        "rtntype": "CODE2",
        "ret_prd": "032019",
    }
]

I want to create a Dictionary in the following format.

{
    "032019" = {
        "CODE1" = {
            "valid": "Y",
            "mof": "ON",
            "dof": "19-04-2019",
            "rtntype": "CODE1",
            "ret_prd": "032019",
            },
        "CODE2" = {
            "valid": "Y",
            "mof": "ON",
            "dof": "19-04-2019",
            "rtntype": "CODE2",
            "ret_prd": "032019",
            "status": "Filed"
        }
    },
    "042019" =  {
        "CODE1" = {
            "valid": "Y",
            "mof": "ON",
            "dof": "17-05-2019",
            "rtntype": "CODE1",
            "ret_prd": "042019",
        }
    }
}

Solution

  • Here is my sample, you can check by yourself

    NSArray *array = @[
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"17-05-2019",@"rtntype":@"CODE1",@"ret_prd":@"042019"},
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE1",@"ret_prd":@"032019"},
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE2",@"ret_prd":@"032019"}
    ];
    
    NSMutableDictionary *result = [NSMutableDictionary new];
        for (int i = 0; i < array.count; i++) {
            NSDictionary *dict = array[i];
            NSString *value = dict[@"ret_prd"];
            if (result[value] == nil) {
                NSArray *filterArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(ret_prd contains[c] %@)", value]];
                NSMutableDictionary *filterDict = [NSMutableDictionary new];
                for (int i = 0; i < filterArray.count; i++) {
                    filterDict[filterArray[i][@"rtntype"]] = filterArray[i];
                }
                result[value] = filterDict;
            }
        }
    
    NSLog(@"%@", result);
    

    Result in console log:

    enter image description here

    Long time no code Objective-C, so above code maybe weird. Let me know if you don't know any where, I'll explain for you.