我们有返回数组的 json 值:
"sentMoney": [
{
"amount": 3840.83,
"currency": "MXN",
"isMajor": false
},
{
"amount": 200,
"currency": "USD",
"isMajor": true
}
]
我想做的是过滤它,这样我就可以获得“金额”键的值。这是我到目前为止所拥有的,但我收到“没有下标成员”错误消息:
let filteredItem = self.postTransferSuccess?.sentMoney.filter{$0["sentMoney"]}[0]
self.emailMessage.amount = filteredItem
感谢任何帮助!
最佳答案
由于您的 sentMoney
是具有 字典数组
的键值,您应该这样做:
let resultObj = (dict["sentMoney"] as? [[String:Any]])?.filter({ ($0["amount"] as? Double) == someValue }).first // dict should be the name of your dictionary
请记住,您的数据应该如下所示,因此不要使用花括号:
var dict = ["sentMoney": [
["amount": 3840.83,"currency": "MXN", "isMajor": false],
["amount": 200.0,"currency": "USD","isMajor": true]
]
]
您的第二个选择是将您的字典转换为结构,这将变得更容易迭代。
struct Item {
let amount:Double
let currency:String
let isMajor:Bool
init?(_ dict:[String:Any]?) { //<-- failable init will return a nil if there an empty key
guard let _dict = dict,
let amount = _dict["amount"] as? Double,
let currency = _dict["currency"] as? String,
let isMajor = _dict["isMajor"] as? Bool
else { return nil }
self.amount = amount
self.currency = currency
self.isMajor = isMajor
}
}
现在当你需要迭代时,你会做: var someValue = 200.0
if let arr = dict["sentMoney"] as? [[String:Any]] {
let items = arr.flatMap({ Item($0)}) //<-- will remove any optional item from your list
let singleItem = items.first { $0.amount == someValue }
// or arr.flatMap({ Item($0) }).filter({ $0.amount == someValue}).first
}
(侧节点)不惜一切代价避免使用 !
,使用 if let 或 guard 语句来解包你的可选值。
关于arrays - 如何过滤数组中特定键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46942475/