我有一个SwiftyJSON
数组嵌套了几个级别,我需要根据最低级别的值过滤数组。下面是一个数组的例子。我需要在Active == true
上过滤它。实现这一目标的最有效方法是什么?
var colors = JSON([
"Apple" : [
"Yellow" : [
"Active" : true,
"Working" : true,
"Value" : 0
],
"Red" : [
"Active" : false,
"Working" : true,
"Value" : 0
]
],
"Banana" : [
"Blue" : [
"Active" : false,
"Working" : true,
"Value" : 0
],
"Green" : [
"Active" : true,
"Working" : true,
"Value" : 0
]
]
])
期望的输出:
"Apple" : [
"Yellow" : [
"Active" : true,
"Working" : true,
"Value" : 0
]
],
"Banana" : [
"Green" : [
"Active" : true,
"Working" : true,
"Value" : 0
]
]
答案 0 :(得分:1)
检查出来
var filteredArray = [JSON]()
for item in colors {
for subItem in item.1 {
if subItem.1["Active"].boolValue {
filteredArray.append(JSON([item.0:JSON([subItem.0:subItem.1])]))
}
}
}
print(filteredArray)
输出是已过滤子词典的词典数组,其中Active为true:
[{
"Apple" : {
"Yellow" : {
"Working" : true,
"Value" : 0,
"Active" : true
}
}
}, {
"Banana" : {
"Green" : {
"Working" : true,
"Value" : 0,
"Active" : true
}
}
}]
答案 1 :(得分:0)
你可以创建一个循环,它将读取所有颜色并在此循环中创建一个将读取第二个数组中其他项目的循环。在第二个是你检查项目是否有效,并将其保存在另一个数组
let activeItems = []
for item in colors {
for i in item as NSDictionary {
if i.objectForKey("Active") == true {
activeItems.addObject(i)
}
}
}
答案 2 :(得分:0)
var result = [String:[String:JSON]]()
for (key, json) in colors.dictionaryValue {
let filtered = json.dictionaryValue.filter{$0.1["Active"].boolValue}
guard filtered.count > 0 else { continue }
var subDic = [String:JSON]()
filtered.forEach{subDic[$0.0] = $0.1}
result[key] = subDic
}
print(result)