【问题标题】:Filter the Dictionary With Array value使用数组值过滤字典
【发布时间】:2019-10-04 12:10:37
【问题描述】:

我有一个包含 ID 的数组

var ID = ["782", "783", "784", "785", "786", "788", "789", "790", "791", "792", "793", "795", "805"]

还有一个类似字典的 Arr

Var arr2 = [["ID":"782","AmenitiesURL":"xyx.com"],["ID":"783","AmenitiesURL":"xybx.com"],["ID":"784","AmenitiesURL":"xyax.com"]]

如图所示。现在我想获取ID的url。

例如。如果 arr ID= 784 然后我想在 arr2 中找到 ID 并获取他们的 url 并附加到新数组中,

简而言之,两个数组一个用于ID,另一个用于URL

【问题讨论】:

  • 将字典数组更改为结构体数组。 IMO 你不应该首先拥有 dict 数组。

标签: ios arrays filtering


【解决方案1】:

另一种方法。虽然这个保留了arr2的结构

let filteredArray = arr2.filter { dict -> Bool in
    for id in ID{
        if dict["ID"] == id{
            return true
        }
    }
    return false
}

【讨论】:

    【解决方案2】:

    获取特定id的URL

    let id = "784"
    if let dict = arr2.first(where: { $0["ID", default:""] == id }), let urlString = dict["AmenitiesURL"] {
        print(urlString)
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用以下方法使其正常工作:

      let urls = ID.compactMap { (id) in
          return arr2.first(where: {$0["ID"] == id})?["AmenitiesURL"]
      }
      

      输出:

      print(urls) //["xyx.com", "xybx.com", "xyax.com"]
      

      对于ID array 中的所有ID,您将从arr2 array 获得AmenitiesURL 值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-15
        • 2019-03-31
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 2013-05-21
        相关资源
        最近更新 更多