NSDiction的NSArray - 合并具有相同键值对的字典

时间:2014-04-03 21:47:10

标签: ios merge nsarray nsdictionary

我有NSArrayNSDictionary个对象:

[
 {
    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
 }
]

我想将具有相同id值的字典合并到一个字典中,组合所有日期,fromDate和toDate键,获得这样的数组,忽略零值:

[
  {
    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
  }
]

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:4)

除了基本蛮力外,我不知道有什么方法可以做到这一点:

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

答案 1 :(得分:1)

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