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

swift dictionary of dictionaries
swift dictionary to array of tuples
dictionary to array swift
swift reduce
swift dictionary values to array
swift dictionary keys to array
convert array to dictionary swift 5
filter array of dictionary swift 4

I have an array of an questions that can be selected

    "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

How do we reduce this array of dictionary with many keys to an array of dictionary with a single key

    "question_id": 1
    "question_id": 2

You could map your array with something like this:

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

but what's the point of returning dicts with a single key and not just an array of values...(?)

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

Mapping a dictionary from an array - Discussion, returns a dictionary with mapped keys and values based on transformation block. /// multiple items with duplicated keys will be overridden, only the last with a couple of Key: Value for each Element of the array func keyMap<Key: Could this one be a valid proposal or I'm just doing something wrong? Subscripting a dictionary with a key returns an optional value, because a dictionary might not hold a value for the key that you use in the subscript. The next example uses key-based subscripting of the response Messages dictionary with two keys that exist in the dictionary and one that does not.

You can use reduce, then inside its closure get the value corresponding to the key id and store it in a new dictionary under the key 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]

reduce(into:_:), Use the reduce(into:_:) method to produce a single value from the elements of when the result is a copy-on-write type, for example an Array or a Dictionary. Returns a new dictionary containing the keys of this dictionary with the values func reduce<Result>(Result, (Result, (key: Key, value: Value)) -> Result) -> Result. A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order.

enum Const: String {
    case id = "id"
    case questionId = "question_id"

let reduced = dict.reduce([]) {
    guard let element = $1[] else {
        return $0
    return $0 + [[Const.questionId.rawValue: element]]

Or you can just reduce it to an array of ints (just for store ids without any "key" because they're the same in every dictionary)

Dictionary, The most common way to access values in a dictionary is to use a key as a subscript. dictionary with two keys that exist in the dictionary and one that does not. string keys and values that are integer arrays, then sorts each array in- place in on the dictionary to get an immutable copy and then performs additional Swift� We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container. Let’s discuss certain ways in which this can be performed. Method #1 : Using dictionary comprehension + items()

Five useful methods of dictionaries – Hacking with Swift, Dictionaries are one of Swift's most commonly used types, so it's This gives us the transforming behavior of map() without the risk of duplicate keys. conference as the key and the conference names stored as an array: Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary. Syntax: dict.keys()

Create Swift Dictionary from Array � GitHub, return array.reduce([:]) {. (var dict, e) in. if let (key, value) = transformer(element: e ). {. dict[key] = value. } return dict. } } struct Person. {. let name: String. let age: Int. } . An NSDictionary is an 'indexed collection' - every item in the collection has a key and can be retrieved with that key. An object may appear more than once, in that different keys may point to the same object, but a key can only appear once. A dictionary is also a form of 'hash table' if you have a computer science background.

Map, Reduce and Filter in Swift – LearnAppMaking, The reduce() function turns a collection into one value. In recent app projects I' ve used Map, Reduce and Filter on multiple occasions: Several types in Swift, such as Array and Dictionary, have functions that accept� A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

  • The api wants [["question_id": 4], ["question_id": 5], ["question_id": 8]] for the selected questions as parameters.