Reputation: 1254
I'm writing a web app in Fantom language and using afMongo to access a Mongo DB instance. Following the example in afMongo documentation I get the results of a query that I need to iterate through. In a simplified example, the iteration looks like this
class MapListIterator {
Void main(){
[Str:Obj?][] listOfMaps := [,]
listOfMaps.add(
["12345":[
"id":12345,
"code":"AU",
"name":"Australia"
]])
listOfMaps.each |Str:Obj? map| {
echo(map.keys)
keys := map.keys
keys.each {
echo(it)
echo(((Str:Obj?)map[it])["code"])
echo(((Str:Obj?)map[it])["name"])
}
}
}
}
I ran this code in Fantom online playground and it works Ok, but I wonder if it is a cleaner way to iterate through the results. I don't like the casting in my code above. Also, is there a better way to write the nested it-block, please?
EDIT:
Turns out that I was overcomplicating things. This is how the code looks after applying Steve's suggestions:
Str:Country mapOfCountries := [:]
mapOfCountries.ordered = true
listOfMaps := ([Str:Str?][]) collection.findAll
listOfMaps.each {
c := it["code"]
n := it["name"]
mapOfCountries.add(c, Country { code = c ; name = n })
}
Upvotes: 1
Views: 60
Reputation: 5139
I would re-cast the result and assign the map early on... which gives:
listOfMappedMaps := ([Str:[Str:Obj?]][]) listOfMaps
listOfMappedMaps.each {
map := it
map.keys.each {
echo(map[it]["code"])
echo(map[it]["name"])
}
}
The next step would be use Morphia which lets you use objects in place of maps.
Upvotes: 1