[英]Retrieve NSDictionary from NSArray where dictionary key has value X
[英]Filter NSArray of NSDictionary , where the dictionary is of type <key , NSDictionary>
我有一個這樣的NSArray
[{“ 268”:{“ name”:“ abc”,“ age”:“ 28”}}},{“ 267”:{“ name”:“ xyz”,“ age”:“ 25”}}]
現在,我要代表鍵對其進行過濾(意味着268、267)。 例如:如果用戶搜索7,則需要顯示
[{“ 267”:{“ name”:“ xyz”,“ age”:“ 25”}}]
let filterText : String = "7"
let array : [Dictionary<String,Any>] = [ ["268" : [ "name" : "abc", "age" : "28"]], [ "267" : [ "name" : "xyz","age" : "25"] ] ]
let result = array.filter { (dictinory) -> Bool in
if let firstKey = dictinory.keys.first {
return firstKey.contains(filterText)
}
return false
}
您可以在Objective-C中使用帶有塊的NSPredicate對其進行過濾:
NSString *searchText = @"8";
NSArray *data = @[@{ @"268" : @{ @"name" : @"abc", @"age" : @"28"} }, @{ @"267" : @{ @"name" : @"xyz",@"age" : @"25"}}];
NSPredicate *predicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
NSDictionary *dict = (NSDictionary *)obj;
NSString *key = dict.allKeys.firstObject;
return [key containsString:searchText];
}];
NSArray *filteredData = [data filteredArrayUsingPredicate:predicate];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.