我有一系列带有类别的选项词典。我希望选项属于该类别。截至目前,我的类别重复了我的选项添加次数。
鉴于此:
(
{
multiOptnCatId = 4;
multiOptnItem = 1344;
},
{
multiOptnCatId = 7;
multiOptnItem = 2253;
},
{
multiOptnCatId = 4;
multiOptnItem = 1343;
},
{
multiOptnCatId = 4;
multiOptnItem = 1346;
},
{
multiOptnCatId = 4;
multiOptnItem = 1342;
},
{
multiOptnCatId = 4;
multiOptnItem = 1345;
}
)
我可以将它转换为有效的方式:
(
{
multiOptnCatId = 4;
multiOptnItem = (1342, 1343, 1344, 1345, 1346);
},
{
multiOptnCatId = 7;
multiOptnItem = (2253);
}
)
谢谢你们! :)
答案 0 :(得分:2)
NSArray *array = ...; // your input array
// All categories as array:
NSArray *catArray = [array valueForKey:@"multiOptnCatId"];
// All categories as set (to remove duplicates):
NSSet *catSet = [NSSet setWithArray:catArray];
NSMutableArray *rearranged = [NSMutableArray array];
// For all categories ...
for (NSString *cat in catSet) {
// Get matching dictionaries for this category:
NSArray *filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"multiOptnCatId = %@", cat]];
// Get "multiOptnItem" values for this category:
NSArray *items = [filtered valueForKey:@"multiOptnItem"];
// Add category + multiOptnItem values to rearranged array:
[rearranged addObject:@{@"multiOptnCatId":cat, @"multiOptnItem":items}];
}