Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search from array of SwiftyJSON objects?

I have an SwiftyJSON object.

How to search by key(name) from the array of SwiftyJSON object.

For Example :

let arrCountry = [JSON]()

Now one country array contains

{
    countryid : "1"
    name : "New York"
},
{
    countryid : "2"
    name : "Sydeny"
}

How to search by predicate or something?

If I search "y" from the array then it should return both object (Because both contains "y") in another JSON array. And If I type "Syd" then it should return only one object in JSON array. As LIKE query in SQL. And as we are doing with predicates...

like image 503
Ashish Kakkad Avatar asked Dec 24 '22 05:12

Ashish Kakkad


1 Answers

Get the array from the JSON object with arrayObject, cast it to the proper type and apply the filter function, in this example to find the item whose name is def

if let array = arrCountry.arrayObject as? [[String:String]],
   foundItem = array.first(where: { $0["name"] == "def"}) {
   print(foundItem)
}

Edit: For a refined search with NSPredicate and a JSON result use this

let searchText = "y"
let searchPredicate = NSPredicate(format: "name contains[cd] %@", searchText)
if let array = arrCountry.arrayObject as? [[String:String]] {
    let foundItems = JSON(array.filter{ searchPredicate.evaluateWithObject($0) })
    print(foundItems)
}
like image 111
vadian Avatar answered Dec 26 '22 20:12

vadian