繁体   English   中英

如何在字典数组中的内部数组上应用过滤器?

[英]how to apply filter on inside array in array of dictionary?

我有一种情况,例如我有字典数组,其中每个键都有特定对象的数组。 像这样。

    // example setup
    struct FruitsData {
        var name: String?
        var id: String?
    }

tableViewSource = [String : [FruitsData]]

所以我必须在这个内部数组上应用过滤器。 但是我无法更新最终数组中的值。 我已经写了这段代码。

tableViewSource = tableViewSource.filter { ( dictData: (key: String, value: [FruitsData])) -> Bool in
    var arrFruitsData = dictData.value
    arrFruitsData = arrFruitsData.filter{ ( $0.id != nil) }

    if arrFruitsData.count == 0 {
        self.tableViewHeaders = self.tableViewHeaders.filter { $0 != dictData.key }
    }
    return true

    }

就像我已经删除了ID已删除的数组中的那些值。

例如,如果我在数组中有这些值。

var array = ["A": [FruitsData(name: "apple", id: "5"), FruitsData(name: "apricot",id: "")], "M": [FruitsData(name: "mango", id: "9"),    FruitsData(name: "grapes", id: "")]]

首先, tableViewSource不是Dictionary的Array ,而是每个具有Array作为值的键的Dictionary 同样从您的示例中, id不是nil而是empty如果您想删除id为nil或为emptyFruitsData对象,可以使它像这样。

var tableViewSource = [String : [FruitsData]]()
tableViewSource.forEach {
    let res = $1.filter { $0.id != nil && $0.id != "" }
    tableViewSource[$0] = res
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM