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

时间:2019-11-18 11:12:53

标签: ios arrays swift dictionary

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

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

3 个答案:

答案 0 :(得分:2)

您可以使用以下内容映射数组:

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

答案 1 :(得分:0)

您可以使用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)

答案 2 :(得分:0)

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,因为每个字典中的ID都相同)