PlanB
PlanB

Reputation: 37

Swift - how to change values of one key in an array of dictionaries using another array

I have an array of 3 dictionaries which looks something like this:

array1 = [["measure1":"90", "measure2":"200","measure3":"23", "measure4":"190"],["measure1":"60", "measure2":"340","measure3":"531", "measure4":"2000"],["measure1":"210", "measure2":"2","measure3":"12", "measure4":"743"]]

Then I also have an array like this:

array2 = ["10","20","30"]

I am trying to replace all the values of "measure4" in the array of dictionaries with the values in array2, in order (i.e. the first "measure4" becomes "10", the second "20" etc)

It feels like the answer should be simple, but i've been trying various different for in loops and nothing brings out the correct array of dictionaries, which should look like this:

array1 = [["measure1":"90", "measure2":"200","measure3":"23", "measure4":"10"],["measure1":"60", "measure2":"340","measure3":"531", "measure4":"20"],["measure1":"210", "measure2":"2","measure3":"12", "measure4":"30"]]

Any help is much appreciated.

Upvotes: 0

Views: 60

Answers (3)

Joakim Danielson
Joakim Danielson

Reputation: 51892

array1[0]["measure4"]? = array2[0]
array1[1]["measure4"]? = array2[1]
array1[2]["measure4"]? = array2[2]

or as a loop

for i in 0..<min(array1.count, array2.count) {
    array1[i]["measure4"]? = array2[i]
}

Upvotes: 0

Fabio Felici
Fabio Felici

Reputation: 2906

Try this code:

let new = array1.enumerated().reduce([[String: String]](), { acc, elemEnumerated in
    var mutableDict = elemEnumerated.element
    mutableDict["measure4"] = array2[elemEnumerated.offset]
    return acc + [mutableDict]
})

Upvotes: 0

meggar
meggar

Reputation: 1219

for (i, x) in array2.enumerated() {
    array1[i]["measure4"] = x
}

Upvotes: 2

Related Questions