【问题标题】:How to filter a nested SwiftyJSON array如何过滤嵌套的 SwiftyJSON 数组
【发布时间】:2016-10-11 20:15:29
【问题描述】:

我有一个嵌套多个级别的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
        ]
]

【问题讨论】:

  • 数组是一个字典。
  • @MikeDeluca 检查我的答案一次。

标签: json swift swifty-json


【解决方案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
    }
  }
}]

【讨论】:

    【解决方案2】:

    您可以创建一个读取所有颜色的循环,并在此循环中创建一个读取第二个数组中其他项目的循环。第二个是检查项目是否有效并将其保存在另一个数组中

    let activeItems = []
    
    for item in colors {
       for i in item as NSDictionary {
          if i.objectForKey("Active") == true {
             activeItems.addObject(i)
          }
       }
    }
    

    【讨论】:

    • 这不起作用,因为数组是 JSON,给出错误cannot convert value of type (String, JSON) to type NSDictionary
    • 不是一个数组。
    • @MikeDeluca 不需要转换成NSDictionary,可以通过SwiftyJSON的简单[JSON]数组来解决。检查我的答案
    【解决方案3】:
            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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2022-12-31
      • 2018-07-28
      • 1970-01-01
      相关资源
      最近更新 更多