繁体   English   中英

在 Swift 中将具有多个键的字典数组减少为具有单个键的字典数组

[英]Reduce an array of dictionary with many keys to an array of dictionary with a single key in Swift

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

[
  {
    "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
  }
]

你可以用这样的东西 map 你的阵列:

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"]
}

您可以使用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)
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,因为它们在每个字典中都是相同的)

暂无
暂无

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

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