我有一个包含字典的数组。在每个字典中再次包含字典数组。我想弄清楚所有具有特定价值的物体,比如印度。 我试过NSpredicate。示例字典数组
{
Destination : [
{
plan : [
{
name : "India"
},
{
name : "India"
}
]
},
{
plan : [
{
name : "Germany"
},
{
name : "Germany"
}
]
}
]
}
对于这本词典,我的代码是
NSMutableArray * destinationArray = [[NSMutableArray alloc]init];
[destinationArray addObject:[ResponseObject objectForKey:@"Destination"]];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",@"India"];
NSArray * filtered = [destinationArray filteredArrayUsingPredicate:predicate];
答案 0 :(得分:0)
NSMutableArray* container = [NSMutableArray new];
for (NSMutableDictionary* d in firstArray) {
for (NSMutableDictionary* d2 in d[@"plan"]) {
[container addObject: [d2[@"name"] mutableCopy];
}
}
我相信这会做到这一点
答案 1 :(得分:0)
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",[[[ResponseObject objectAtIndex:i]objectForKey:@"destination"]objectForKey:@"name"]];
在您的代码中,当在此处致电[[ResponseObject objectAtIndex:i]objectForKey:@"destination"]
时,NSArray
包含一些NSDictionary
。当你拨打objectForKey:@"name"
时,它会向你发送错误,你确定你的代码是最新的吗?
这是我的测试跟随你的数据结构,结果是最新的。
NSArray *array = @[@{@"name" : @"zhangsan",
@"age" : @"10",
@"result": @[
@{@"res":@"123l"},
@{@"res":@"789l"}
]
},
@{@"name" : @"lisi",
@"age" : @"11",
@"result": @[
@{@"res":@"123l"},
@{@"res":@"789l"}
]
},
@{@"name" : @"wangwu",
@"age" : @"12",
@"result": @[
@{@"res":@"123l"},
@{@"res":@"789l"}
]
}];
NSString *preStr = @"res";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS[c] %@",preStr, @"123"];
NSMutableArray *result = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSArray *res = dict[@"result"];
[result addObjectsFromArray:[res filteredArrayUsingPredicate:predicate]];
}
NSLog(@"final result == %@",result);