Search code examples
javahashmapthymeleaf

Iterate a HashMap with nested HashMap values in javascript by using thymeleaf


This is the object added to the model:

HashMap<String,HashMap<String,Integer>> eventByMonthAndYear;

How I tried to iterate it

I've tried these solutions but none has worked so far for me.

Iterate HashMap using thymeleaf

My efford

<script  type="text/javascript" th:inline="javascript">


/*<![CDATA[*/

   /*[# th:each="entry: ${eventByMonthAndYear}"]*/

    console.log(/*[[${entry}]]*/);
    
    /*[/]*/     
    
/*]]>*/

</script>

No object is printed, how can i at-least retrieve the first HashMap?


Solution

  • Assume we have the following test data:

    Map<String, Integer> intMapA = new HashMap();
    intMapA.put("one", 1);
    intMapA.put("two", 2);
    intMapA.put("three", 3);
            
    Map<String, Integer> intMapB = new HashMap();
    intMapB.put("four", 4);
    intMapB.put("five", 5);
    intMapB.put("six", 6);
            
    Map<String, Map<String, Integer>> eventByMonthAndYear = new HashMap();
    eventByMonthAndYear.put("Event A", intMapA);
    eventByMonthAndYear.put("Event B", intMapB);
           
    Map<String, Object> model = new HashMap();
    model.put("events", eventByMonthAndYear);
    

    This is what gets passed to the Thymeleaf template.

    We can access the events object in Javascript as follows:

    <script th:inline="javascript">
        var events = [[${events}]];
        console.log(events);
    </script>
    

    You can iterate the variable in the usual JS way.

    What may be of more use is to access the object in the HTML and iterate over the nested maps using Thymeleaf:

        <body>
            <div th:each="event : ${events}">
                <div th:text="${event.key}">
                </div>
                <div th:each="eventItem : ${event.value}">
                    <div th:text="${' -> ' + eventItem.key} + ' - ' + ${eventItem.value}"></div>
                </div>
            </div>
        </body>
    

    This last example displays the following in the browser:

    Event B
    -> six - 6
    -> four - 4
    -> five - 5
    Event A
    -> one - 1
    -> two - 2
    -> three - 3
    

    Obviously, because of our specific use of hashmaps, the order of retrieval is not guaranteed to be the same as the insertion order.