基于NSDictionay中的键对NSDictionary的NSArray进行分组 [英] Grouping NSArray of NSDictionary based on a key in NSDictionay
问题描述
我试图过滤出一个NSArray的NSDictionaries。在我的下面的例子,我想dict1,dict2& dict4分组在一个数组中,dict3& dict5分组在第二个数组中,dict6在第三个数组中。
I am trying to filter out a NSArray of NSDictionaries. With my below example, I want dict1, dict2 & dict4 grouped in one array, dict3 & dict5 grouped in second array and dict6 in third array.
我在NSArray中获取这些数据,因此下面的orig数组是我的输入,我知道我需要基于Name键进行分组。
I am getting this data in NSArray, so essentially the "orig" array below is my input and I know that I need to do grouping based on "Name" key.
而不是循环通过NSArray我虽然使用valueForKeyPath基于键路径返回我的数组,但这不工作(崩溃与日志 - [NSMutableArray addObjectsFromArray:] :数组参数不是NSArray')。
Instead of looping through the NSArray I though of using valueForKeyPath to return me array based on the key path but this does not work (crashes with logs -[NSMutableArray addObjectsFromArray:]: array argument is not an NSArray').
任何建议。
NSDictionary *dict1 = @{@"Name" : @"T1", @"Age" : @"25"};
NSDictionary *dict2 = @{@"Name" : @"T1", @"Age" : @"25"};
NSDictionary *dict3 = @{@"Name" : @"T2", @"Age" : @"27"};
NSDictionary *dict4 = @{@"Name" : @"T1", @"Age" : @"25"};
NSDictionary *dict5 = @{@"Name" : @"T2", @"Age" : @"27"};
NSDictionary *dict6 = @{@"Name" : @"T3", @"Age" : @"28"};
NSArray *orig = @[dict1, dict2, dict3, dict4, dict5, dict6];
NSMutableArray *final = [NSMutableArray array];
final = [orig valueForKeyPath:@"@unionOfArrays.Name"];
NSLog(@"Final = %@", final);
推荐答案
这很难说,三个不同的数组,其中每个只包含具有特定 Name
值的条目(如您的第一段建议),或者如果您想要一个数组,其中条目按 Name
(正如你的第二段建议)。无论如何,
It's a little hard to tell if what you want is three different arrays where each one only contains entries with a specific Name
value (as your first paragraph suggests) or if you want a single array where the entries are sorted by Name
(as your second paragraph suggests). Regardless,
按名称的值对
orig
c> field:
To sort orig
by the value of the Name
field:
NSArray *sortedByName = [orig sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"Name" ascending:YES]]];
要通过仅选择名称的特定值的条目来获取新数组
:
NSArray *t1Only = [orig filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"Name = %@", @"T1"]];
这篇关于基于NSDictionay中的键对NSDictionary的NSArray进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!