Map value the particular key wherever presents in array of dictionary and replace it in same array.
We need to update pan_card key 0 to 1, in occurence of array of dictionary.
let keyToUpdate = "pan_card"
var arrayOfDictionary = [[String:Any]]()
var firstDict = [String:Any]()
firstDict["passport"] = 0
firstDict["ration_card"] = 0
firstDict["pan_card"] = 0
var arrayDict = [String : Any]()
arrayDict["currentObject"] = firstDict
arrayDict["title"] = "Documents list"
var secondDict = [String:Any]()
secondDict["dl"] = 0
secondDict["voter"] = 0
secondDict["pan_card"] = 0
//let dic = secondDict.filter({ $0.value as! NSNumber != 0})
//secondDict = dic
//print(secondDict)
//let dictionary = ["foo": 1, "bar": 2, "baz": 5]
//
//let newDictionary = dictionary.mapValues { value in
// return value - value
//}
//print(dictionary)
//print(newDictionary)
var arrayDict2 = [String : Any]()
arrayDict2["currentObject"] = secondDict
arrayDict2["title"] = "Second Documents list"
arrayOfDictionary.append(arrayDict)
arrayOfDictionary.append(arrayDict2)
//print(arrayOfDictionary)
for (index, dictionary) in arrayOfDictionary.enumerated() {
let dict = dictionary
let newDictionary = (dict["currentObject"] as![String:Any]).mapValues { value in
return 1
}
arrayOfDictionary[index] = newDictionary
}
print(arrayOfDictionary)
This code updating every key in currentObject
and tried this as well, but it adding new key
for (index, dictionary) in arrayOfDictionary.enumerated() {
var dict = dictionary
// let newDictionary = (dict["currentObject"] as![String:Any]).mapValues { value in
// return 1
// }
var newDictionary = [String: Any]()
for (key, value) in dict["currentObject"] as![String:Any] {
dict[keyToUpdate, default: value] = 1
}
arrayOfDictionary[index] = dict
}
print(arrayOfDictionary)
I need output like below
Original value
[["currentObject": ["passport": 0, "pan_card": 0, "ration_card": 0], "title": "Documents list"], ["currentObject": ["pan_card": 0, "dl": 0, "voter": 0], "title": "Second Documents list"]]
after update
[["currentObject": ["passport": 0, "pan_card": 1, "ration_card": 0], "title": "Documents list"], ["currentObject": ["pan_card": 1, "dl": 0, "voter": 0], "title": "Second Documents list"]]
Referred Document Link
We knows manually iterating and updating values, we wanted to done with higher order function.
Using a recursive method that performs the update
we can use a simple
map
callThe
update
function was based on this answer