如何从 SwiftyJSON 对象数组中搜索? [英] How to search from array of SwiftyJSON objects?

查看:35
本文介绍了如何从 SwiftyJSON 对象数组中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SwiftyJSON 对象.

I have an SwiftyJSON object.

如何从 SwiftyJSON 对象数组中按键(名称)进行搜索.

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

例如:

let arrCountry = [JSON]()

现在一个国家数组包含

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

如何通过谓词或其他方式进行搜索?

How to search by predicate or something?

如果我从数组中搜索y",那么它应该在另一个 JSON 数组中返回两个对象(因为两者都包含y").如果我输入Syd",那么它应该只返回 JSON 数组中的一个对象.作为 SQL 中的 LIKE 查询.正如我们对谓词所做的那样......

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...

推荐答案

使用 arrayObjectJSON 对象中获取数组,将其转换为正确的类型并应用filter 函数,在本例中查找 namedef

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)
}

对于带有 NSPredicateJSON 结果的精确搜索,请使用此

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)
}

这篇关于如何从 SwiftyJSON 对象数组中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆