NSDictionaries的NSArray-合并具有相同键值对的字典 [英] NSArray of NSDictionaries - merge dictionaries with same key value pair

查看:99
本文介绍了NSDictionaries的NSArray-合并具有相同键值对的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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键组合在一起,获得一个像这样的数组,该数组将忽略零值:

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?

推荐答案

除了基本的蛮力外,我不知道有什么其他方法可做:

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

这篇关于NSDictionaries的NSArray-合并具有相同键值对的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆