NSArray of NSDictionaries - merge dictionaries wit

2019-06-08 08:58发布

问题:

I have a NSArray of NSDictionary objects:

[
 {
    id = 1;
    fromDate = 2014-04-03;
    toDate = 2014-04-05;
    date = 0000-00-00;
    title = title 1
 },
 {
    id = 1;
    fromDate = 0000-00-00;
    toDate = 0000-00-00;
    date = 2014-04-03
    title = title 1
 },
 {
    id = 1;
    fromDate = 0000-00-00;
    toDate = 0000-00-00;
    date = 2014-04-04;
    title = title 1
 },
 {
    id = 2;
    fromDate = 0000-00-00;
    toDate = 0000-00-00;
    date = 2014-05-10;
    title = title 2
 },
 {
    id = 2;
    fromDate = 0000-00-00;
    toDate = 0000-00-00;
    date = 2014-05-11;
    title = title 2
 }
]

I would like to merge dictionaries with same id value into one dictionary combining all date, fromDate and toDate keys, obtaining an array like this, that ignores zero values:

[
  {
    id = 1,
    combinedDates = 2014-04-03, 2014-04-05, 2014-04-03, 2014-04-04;
    title = title 1
  },
  {
    id = 2,
    combinedDates = 2014-05-10, 2014-05-11;
    title = title 2
  }
]

Can someone point me to the right direction?

回答1:

I don't know of any way to do this other than basic brute force:

-(NSArray*)combinedArray:(NSArray*)array
{
    NSMutableArray*     combined = [NSMutableArray new];

    // Iterate over each unique id value
    for(id key in [NSSet setWithArray:[array valueForKeyPath:@"id"]])
    {
        // skip missing keys
        if([key isKindOfClass:[NSNull class]])
            continue;

        // Sub array with only id = key
        NSArray*        filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary* evaluatedObject, NSDictionary *bindings) {
            return [evaluatedObject valueForKey:@"date"] && [[evaluatedObject valueForKey:@"id"] isEqual:key];
        }]];

        // Grab the dates
        NSArray*        dates = [filtered valueForKeyPath:@"date"];

        // add the new dictionary
        [combined addObject:@{ @"id":key, @"combinedDates":dates }];
    }

    return array;
}


回答2:

// Group By id
-(NSMutableDictionary*)combinedArray:(NSArray*)array
{
    NSMutableArray *categories = [[NSMutableArray alloc] init];
    for (NSDictionary *data in array) {

        NSString *category = [data valueForKey:@"id"];
        if (![categories containsObject:category]) {
            [categories addObject:category];
        }
    }

    NSMutableDictionary *categoryData = [[NSMutableDictionary alloc]init];

    for (NSString *strCat in categories) {

        NSMutableArray *catArray = [[NSMutableArray alloc]init];

        for (NSDictionary *data in array) {

            NSString *category = [data valueForKey:@"id"];

            if ([category isEqualToString:strCat]) {
                [catArray addObject:data];
            }
        }

        [categoryData setObject:catArray forKey:strCat];

    }

    return categoryData;
}