我需要合并两个字典而不重复
第一个喜欢:
{
"Posts": [
{
"id": "1",
"Title": "First post",
"Category": "News"
},
{
"id": "2",
"Title": "Second post",
"Category": "News"
},
{
"id": "3",
"Title": "Third post",
"Category": "News"
}
]
}
第二个像:
{
"Posts": [
{
"id": "3",
"Title": "Third post",
"Category": "News"
},
{
"id": "4",
"Title": "Fourth post",
"Category": "News"
},
{
"id": "5",
"Title": "Fifth post",
"Category": "News"
}
]
}
如何在不重复第三个条目的情况下合并?
任何人都可以提供帮助
答案 0 :(得分:2)
NSDictionary *dic1 = @{
@"Posts" : @[
@{
@"id" : @"1", @"Title" : @"First post", @"Category" : @"News"
}, @{
@"id" : @"2", @"Title" : @"Second post", @"Category" : @"News"
}, @{
@"id" : @"3", @"Title" : @"Third post", @"Category" : @"News"
}
]
};
NSDictionary *dic2 = @{
@"Posts" : @[
@{
@"id" : @"3", @"Title" : @"Third post", @"Category" : @"News"
}, @{
@"id" : @"4", @"Title" : @"Fourth post", @"Category" : @"News"
}, @{
@"id" : @"5", @"Title" : @"Fifth post", @"Category" : @"News"
}
]
};
NSMutableArray *keys = [NSMutableArray new];
[dic1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[keys addObject:dic1[ key ]];
}];
[dic2 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[keys addObject:dic2[ key ]];
}];
NSMutableArray *totalResult = [NSMutableArray new];
[keys enumerateObjectsUsingBlock:^(NSArray *obj, NSUInteger idx, BOOL *stop) {
[obj enumerateObjectsUsingBlock:^(id obj2, NSUInteger idx2, BOOL *stop2) {
NSArray *filtered = [totalResult filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(id == %@)", obj2[ @"id" ]]];
if ( !filtered.count ) {
[totalResult addObject:obj2];
}
}];
}];
NSLog(@"");
答案 1 :(得分:1)
合并两个词典的键(由dict.allKeys
检索的两个单独的数组),并创建一个新词典。但是如果你在allKeys
中获得类似的密钥,你必须创建自己的系统来挑选一两个(或者如果你有两个以上的词典)更多的尊重值。
NSDictionary *dict1=[NSDictionary dictionary];
NSDictionary *dict2=[NSDictionary dictionary];
NSArray *arr1=[dict1 allKeys];
NSArray *arr2=[dict2 allKeys];
NSArray *allKeysArray=[arr1 arrayByAddingObjectsFromArray:arr2];
NSMutableDictionary *newDict=[[NSMutableDictionary alloc]init];
for (NSString *aKey in allKeysArray)
{
BOOL bothArrayContainSameKey=NO;
if ([arr1 containsObject:aKey] && [arr2 containsObject:aKey])
{
bothArrayContainSameKey=YES;
//needs special treatment
}
else if ([arr1 containsObject:aKey])
{
[newDict setObject:dict1[aKey] forKey:aKey];
}
else if ([arr2 containsObject:aKey])
{
[newDict setObject:dict2[aKey] forKey:aKey];
}
}