我有一个NSArray,数组中的每个对象都有一个groupId和一个名字.每个对象是唯一的,但是有很多与同一个groupId.有没有办法我可以拆分阵列并重新构建它,以便将名称分组为具有相应groubId的单个对象?这是数组当前的样子:
2013-03-12 20:50:05.572 appName[4102:702] the array: ( { groupId = 1; name = "Dan"; },{ groupId = 1; name = "Matt"; },{ groupId = 2; name = "Steve"; },{ groupId = 2; name = "Mike"; },{ groupId = 3; name = "John"; },{ groupId = 4; name = "Kevin"; } )
这就是我想要的样子:
2013-03-12 20:50:05.572 appName[4102:702] the array: ( { groupId = 1; name1 = "Dan"; name2 = "Matt"; },{ groupId = 2; name1 = "Steve"; name2 = "Mike"; },{ groupId = 4; name = "Kevin"; } )
编辑:
我试过&失败了许多尝试,大多数沿着这样的事情(马虎的娱乐,但给出一个想法):
int idNum = 0; for (NSDictionary *arrObj in tempArr){ NSString *check1 = [NSString stringWithFormat:@"%@",[arrObj valueForKey:@"groupId"]]; NSString *check2 = [NSString stringWithFormat:@"%@",[[newDict valueForKey:@"groupId"]]; if (check1 == check2){ NSString *nameStr = [NSString stringWithFormat:@"name_%d",idNum]; [newDict setValue:[arrObj valueForKey:@"name"] forKey:nameStr]; } else { [newDict setValue:arrObj forKey:@"object"]; } idNum++; }
解决方法
NSArray *array = @[@{@"groupId" : @"1",@"name" : @"matt"},@{@"groupId" : @"2",@"name" : @"john"},@{@"groupId" : @"3",@"name" : @"steve"},@{@"groupId" : @"4",@"name" : @"alice"},@{@"groupId" : @"1",@"name" : @"bill"},@"name" : @"bob"},@"name" : @"jack"},@"name" : @"dan"},@"name" : @"kevin"},@"name" : @"mike"},@"name" : @"daniel"},]; NSMutableArray *resultArray = [NSMutableArray new]; NSArray *groups = [array valueForKeyPath:@"@distinctUnionOfObjects.groupId"]; for (NSString *groupId in groups) { NSMutableDictionary *entry = [NSMutableDictionary new]; [entry setObject:groupId forKey:@"groupId"]; NSArray *groupNames = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"groupId = %@",groupId]]; for (int i = 0; i < groupNames.count; i++) { NSString *name = [[groupNames objectAtIndex:i] objectForKey:@"name"]; [entry setObject:name forKey:[NSString stringWithFormat:@"name%d",i + 1]]; } [resultArray addObject:entry]; } NSLog(@"%@",resultArray);
输出:
( { groupId = 3; name1 = steve; name2 = jack; name3 = daniel; },{ groupId = 4; name1 = alice; name2 = dan; },{ groupId = 1; name1 = matt; name2 = bill; name3 = kevin; },{ groupId = 2; name1 = john; name2 = bob; name3 = mike; } )