ios swift 3 按字典中键的字符串值过滤字典数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40570716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
swift 3 filter array of dictionaries by string value of key in dictionary
提问by Cory Billeaud
I have a class such as this
我有一堂这样的课
class FoundItem : NSObject {
var id : String!
var itemName : String!
var itemId : Int!
var foundBy : String!
var timeFound : String!
init(id: String,
itemName: String,
itemId: Int,
foundBy: String,
timeFound: String)
{
self.id = id
self.itemName = itemName
self.itemId = itemId
self.foundBy = foundBy
self.timeFound = timeFound
}
and I reference it on my
我在我的
class MapViewVC: UIViewController, MKMapViewDelegate {
var found = [FoundItem]()
var filterItemName : String()
}
My FoundItem
are generated by into an array of dictionaries from my class of FoundItem
from a firebase query. I then get a string of that itemName
that is generated from an another view controller that is a collection view on the didSelection
function. I want to take that string and then filter or search the arrays with the string itemName
that is equal from the itemName
string from my previous viewController
. Then removed the array of dictionaries that are not equal to the itemName
. Not just the objects, but the entire array that contains non-equal key, value pair. I have looked for days, and I am stuck on filtering an array of dictionaries created from a class. I have looked and tried NSPredicates, for-in loops, but all that ends up happening is creating a new array or bool that finds my values or keys are equal. Here is the current function I have written.
MyFoundItem
是从我的类中生成的一组字典,FoundItem
来自 firebase 查询。然后我得到一个字符串,itemName
它是从另一个视图控制器生成的,它是didSelection
函数的集合视图。我想采取的字符串,然后过滤或与搜索字符串数组itemName
是从等于itemName
从我以前的字符串viewController
。然后删除不等于的字典数组itemName
. 不仅仅是对象,而是包含不等键值对的整个数组。我已经找了好几天了,我一直在过滤从一个类创建的字典数组。我已经查看并尝试了 NSPredicates、for-in 循环,但最终发生的只是创建一个新的数组或 bool,发现我的值或键相等。这是我编写的当前函数。
func filterArrayBySearch() {
if self.filterItemName != nil {
dump(found)
let namePredicate = NSPredicate(format: "itemName like %@", "\(filterItemName)")
let nameFilter = found.filter { namePredicate.evaluate(with: var dict:[[String:AnyObject]] = sortedArray.filter{(var dict = sortedArray.filter{( let dict = sortedArray.filter{ ( func updateSearchResults(for searchController:
UISearchController) {
if (searchController.searchBar.text?.characters.count)! > 0 {
guard let searchText = searchController.searchBar.text,
searchText != "" else {
return
}
usersDataFromResponse.removeAll()
let searchPredicate = NSPredicate(format: "userName
CONTAINS[C] %@", searchText)
usersDataFromResponse = (filteredArray as
NSArray).filtered(using: searchPredicate)
print ("array = \(usersDataFromResponse)")
self.listTableView.reloadData()
}
}
["parentId"] as! String) == "compareId" }.first
["parentId"] as! String) == "compareId"}.first
["parentId"] as! String) == "compareId"}
) }
var crossRefNames = [String: [FoundItem]]()
for nameItemArr in found {
let listName = nameItem.itemName
let key = listName
if crossRefNames.index(forKey: key!) != nil {
crossRefNames[key!]?.append(nameItemArr)
if !("\(key)" == "\(filterItemName!)") {
print("------------- Success have found [[[[[[ \(key!) ]]]]]] and \(filterItemName!) to be equal!!")
// crossRefNames[key!]?.append(nameItemArr)
} else {
print("!! Could not find if \(key!) and \(filterItemName!) are equal !!")
}
} else {
crossRefNames[key!] = [nameItemArr]
}
}
} else {
print("No Data from Search/FilterVC Controller")
}
}
Can anyone help? It seems like it would be the simple task to find the value and then filter out the dictionaries that are not equal to the itemName
string, but I keep hitting a wall. And running into for-in loops myself :P trying different things to achieve the same task.
任何人都可以帮忙吗?似乎找到值然后过滤掉不等于itemName
字符串的字典是一项简单的任务,但我一直在碰壁。我自己也遇到了 for-in 循环 :P 尝试不同的事情来完成相同的任务。
回答by par
I hope I understood what you were asking. You mention an "array of dictionaries" but you don't actually have an array of dictionaries anywhere in the code you've posted.
我希望我明白你在问什么。您提到了“字典数组”,但实际上在您发布的代码中的任何地方都没有字典数组。
As far as I can tell, you are asking how to find all the entries in the found
array for which itemName
equals the filterItemName
property.
据我所知,您问的是如何在found
数组中找到itemName
等于该filterItemName
属性的所有条目。
If so, all you should need to do is:
如果是这样,您需要做的就是:
let foundItems = found.filter { $0.itemName == filterItemName }
let foundItems = found.filter { $0.itemName == filterItemName }
That's it.
就是这样。
Some other ideas:
其他一些想法:
If you want to search for items where filterItemName
is contained in the itemName
, you could do something like this:
如果您想搜索filterItemName
包含在 中的项目itemName
,您可以执行以下操作:
let foundItems = found.filter { $0.itemName.contains(filterItemName) }
let foundItems = found.filter { $0.itemName.contains(filterItemName) }
You could also make use of the lowercased()
function if you want to do case-insensitive search.
lowercased()
如果您想进行不区分大小写的搜索,也可以使用该功能。
You could also return properties of your found elements into an array:
您还可以将找到的元素的属性返回到数组中:
let foundIds = found.filter { $0.itemName == filterItemName }.map { $0.itemId }
let foundIds = found.filter { $0.itemName == filterItemName }.map { $0.itemId }
回答by IKKA
Sort array of dictionary using the following way
使用以下方式对字典数组进行排序
var searchDict = dict.filter { (arg0) -> Bool in
let (key, value) = arg0
for paymentInfo in (value as! [PaymentInfo]){
let organization = (Array((value as! [PaymentInfo])[0].paymentToInvoice!)[0] as! InvoiceInfo).invoiceToPeople?.organization
let firstName = (Array((value as! [PaymentInfo])[0].paymentToInvoice!)[0] as! InvoiceInfo).invoiceToPeople?.firstName
let lastName = (Array((value as! [PaymentInfo])[0].paymentToInvoice!)[0] as! InvoiceInfo).invoiceToPeople?.lastName
return organization?.localizedStandardRange(of: searchText) != nil || firstName?.localizedStandardRange(of: searchText) != nil || lastName?.localizedStandardRange(of: searchText) != nil
}
return true
}
The?filter?function loops over every item in a collection, and returns a collection containing only items that satisfy an include condition.
这?filter?function 循环遍历集合中的每个项目,并返回一个仅包含满足包含条件的项目的集合。
We can get single object from this array of dictionary , you can use the following code
我们可以从这个字典数组中获取单个对象,您可以使用以下代码
##代码##OR
或者
##代码##回答by Gangireddy Rami Reddy
Local search filter using predicate in array of dictionary objects with key name this code use for both swift3 and swift4,4.1 also.
本地搜索过滤器在字典对象数组中使用谓词,键名此代码也用于 swift3 和 swift4,4.1。
##代码##回答by Yogesh Patel
Here I use CoreData And I have Array of Dictionary . Here I am filter the key paymentToInvoice that value is invoice array then key invoiceToPeople that key contain People Dictionary then I search FirstName, lastName, Organization multiple key contain searchText. I hope it's helps Please try this Thank You
在这里,我使用 CoreData 并且我有 Array of Dictionary 。在这里,我过滤了值是发票数组的键 paymentToInvoice,然后是键包含人物字典的键发票人,然后我搜索名字、姓氏、组织多个键包含搜索文本。我希望它有帮助请试试这个谢谢
##代码##