我试图找到一个很好的解决方案,将一个字典数组拆分为一个较小的字典,这些字典由它们之间的共同值键入。
这是我的 JSON 示例,我从这里开始:
{
"field": [
{
"id": 6,
"name": "Andrea"
},
{
"id": 67,
"name": "Francesco"
},
{
"id": 8,
"name": "Maria"
},
{
"id": 6,
"name": "Paolo"
},
{
"id": 67,
"name": "Sara"
}
]
}
我想得到如下结果:
{
"field": [
{
"6": [
{
"name": "Andrea",
"id": 6
},
{
"name": "Paolo",
"id": 6
}
],
"67": [
{
"name": "Sara",
"id": 67
},
{
"name": "Francesco",
"id": 67
}
],
"8": [
{
"name": "Maria",
"id": 8
}
]
}
]
}
我使用此代码进行了管理,它可以工作,但我想知道是否存在更正确和快速的东西:
NSArray * array = ...;
NSSortDescriptor *sorter1=[[NSSortDescriptor alloc]initWithKey:@"id" ascending:YES selector:@selector(compare:)];
NSSortDescriptor *sorter2=[[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors=[NSArray arrayWithObjects:sorter1,sorter2,nil];
array = [array sortedArrayUsingDescriptors:sortDescriptors];
//////////////////////////////SPLITTER
NSMutableArray * subcategorySplittedArray = [[NSMutableArray alloc]initWithCapacity:30];
NSNumber * lastID=[[array objectAtIndex:0]objectForKey:@"id"];
NSMutableArray * shopArray = [[NSMutableArray alloc]initWithCapacity:100];
NSMutableDictionary * catDict = nil;
for (NSDictionary * dict in array) {
NSNumber * catID = [dict objectForKey:@"id"];
if ([lastID isEqualToNumber:catID]) {
[shopArray addObject:dict];
}
else {
catDict = [[NSMutableDictionary alloc]init ];
[catDict setObject:[shopArray copy] forKey:lastID];
[subcategorySplittedArray addObject:catDict];
[shopArray removeAllObjects];
[shopArray addObject:dict];
lastID = catID;
}
}
catDict = [[NSMutableDictionary alloc]init ];
[catDict setObject:[shopArray copy] forKey:lastID];
[subcategorySplittedArray addObject:catDict];
////////////////////////////////////
return subcategorySplittedArray;
}