Search code examples
groovygsp

Get the values of maps in arrayList


I have an arrayList of maps that i generate in my controller and pass to GSP page!

i would like to get the values of the maps as a list to present in g:select in gsp!

as in each element (Map) in the arrayList! The select option value should be the map value and the map key as an optionKey as i want to use this key in a script when the user choose an option!

sorry am a bit confused if the question is not quite clear!

 ArrayList[Map1,Map2,Map3]
    Map1[1,value1]
    Map2[2,value2]
    Map3[3,value3]
    // the values are strings to show in select
   //the respective key of the option value the user has chosen i want it as option key so i can pass it to script

Solution

  • If I understood correctly you have a list (ArrayList) of Maps and you want to represent each map as a select, right?

    Your arraylist of maps could be something like this:

    def words_en = ['One':'Apple', 'Two':'Pear', 'Three': 'Strawberry']
    def words_it = ['One':'Mela', 'Two':'Pera', 'Three': 'Fragola']
    def words_de = ['One':'Apfel', 'Two':'Birne', 'Three': 'Erdbeere']
    
    def myList = [words_en, words_it, words_de]
    

    you can generate the select elements as follows:

    <g:each var="myMap" in="${myList}" status="i">
        <g:select id="select_${i}" name="select_${i}" optionKey="key" from="${myMap}" optionValue="value" ></g:select> <br/>
    </g:each>
    

    EDIT: With the edited version of your question I understood that you have several maps each containing only one key-value pair. Given that your keys are unique, the best approach is to merge all your maps into one and simply use that to populate the select:

    def words_1 = ['One':'Apple']
    def words_2 = ['Two':'Pera']
    def words_3 = ['Three': 'Erdbeere']
    
    def myList = [words_1, words_2, words_3]
    
    def myMap = [:]
    myList1.each{map->
        myMap.putAll(map)
    }
    

    and in the view:

    <g:select id="mySelect" name="mySelect" optionKey="key" from="${myMap}" optionValue="value" ></g:select>