【问题标题】:Reduce an array of dictionary with many keys to an array of dictionary with a single key in Swift在 Swift 中将具有多个键的字典数组减少为具有单个键的字典数组
【发布时间】:2019-11-18 11:12:53
【问题描述】:

我有一系列可以选择的问题

[
  {
    "id": 1,
    "title": "test",
    "info": "Test123",
    "is_selected": true
  },
  {
    "id": 2,
    "title": "test2",
    "info": "test2",
    "is_selected": false
  },
  {
    "id": 3,
    "title": "test23",
    "info": "test23",
    "is_selected": true
  }
]

我们如何将这个包含许多键的字典数组缩减为具有单个键的字典数组

[
  {
    "question_id": 1
  },
  {
    "question_id": 2
  }
]

【问题讨论】:

    标签: ios arrays swift dictionary


    【解决方案1】:

    你可以用这样的东西来映射你的数组:

    let secondArray: [[String : Int]] = array.compactMap { dict in
        guard let id = dict["id"] as? Int else { return nil }
        return ["question_id" : id]
    }
    

    但是用一个键返回字典有什么意义,而不仅仅是一个值数组...(?)

    let questionIds = array.compactMap { dict in
        return dict["id"]
    }
    

    【讨论】:

    • API 需要 [["question_id": 4], ["question_id": 5], ["question_id": 8]] 作为参数选择的问题。
    【解决方案2】:

    您可以使用reduce,然后在其闭包中获取与键id 对应的值,并将其存储在键question_id 下的新字典中。

    let dictionariesWithSingleKey = dictionariesWithManyKeys.reduce(into: [[String:Int]](), { result, current in
        guard let questionId = current["id"] as? Int else { return }
        let singleKeyedDict = ["question_id": questionId]
        result.append(singleKeyedDict)
    })
    print(dictionariesWithSingleKey)
    

    【讨论】:

      【解决方案3】:
      enum Const: String {
          case id = "id"
          case questionId = "question_id"
      }
      
      let reduced = dict.reduce([]) {
          guard let element = $1[Const.id.rawValue] else {
              return $0
          }
          return $0 + [[Const.questionId.rawValue: element]]
      }
      

      或者您可以将其简化为整数数组(仅适用于没有任何“键”的商店 ID,因为它们在每个字典中都是相同的)

      【讨论】:

        猜你喜欢
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 2021-03-13
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多