Search to JSON in swift -
i trying find matching keyword in json. example want object contains sam in either title, number or array of users.
[ { "title":"list of students", "number": "12 stu", "users":[{ "id": 12, "name":"tom" }, { "id": 1, "name":"sam" }] }, { "title":"list of tutors", "number": "2 tut", "users":[{ "id": 1, "name":"john" }, { "id": 1, "name":"sam" }] } ] with code, can search through title , number cant search through each users.
func searchbar(_ searchbar: uisearchbar, textdidchange searchtext: string) { arrresf = arrres.filter({ (item) -> bool in let heading: nsstring = ((item["title"]! as? string)! + (item["number"]! as! string)) nsstring return (heading.range(of: searchtext, options: nsstring.compareoptions.caseinsensitive).location) != nsnotfound }) self.tableview.reloaddata() } how expand search include users.
thanks.
result = array.filter { item in let title = item["title"] as? string ?? "" let number = item["number"] as? string ?? "" let users = (item["users"] as? [[string: any]]) ?? [] let usersstring = users.reduce("") { result, dictionary in [result, dictionary["name"]].flatmap { $0 }.joined(separator: "\t") } let finalstring = [title, number, usersstring].joined(separator: "\t") return finalstring.lowercased().contains(searchterm.lowercased()) } since users array of dictionaries, use reduce, helps "reduce" array single value. i'm doing here going through dictionaries in array , adding value name string.
a couple of details:
- you should avoid converting swift objects
nsobjects when possible. make code cleaner. - force-unwrapping optionals should avoided, if dictionary doesn't have value "title" in code, crash. it's better use default value operator
?? - while can work dictionaries, recommend creating
structcan initialized json dictionary.
Comments
Post a Comment