Search code examples
freemarker

Combine two freemarker hash with same key inside table


My two hash/maps are as below. I want to get the value corresponding to the key from the first map and second map and then add them to table

Map 1 [ { "key": "1", "value":"Potato" }, { "key": "2", "value":"Chilly" } ]

Map 2 [ { "key": "1", "value":"Apple" }, { "key": "2", "value":"Plum" } ]

I want the data in the fashion so that I can fetch data for the same key from both the map at the same time

<#list map1+map2?keys as key>
<tr>
    <td>${key}</td>
    <td >${map1[key]}</td>
    <td >${map2[key]}</td>
</tr>
</#list>

I know I am doing something wrong, but not able to process the code. Can someone help?


Solution

  • You need to parenthesize the map concatenation in order to be able to use the built-in ?keys, so (map1 + map2)?keys. Also, you might want to check for empty values if the maps are not equal by suffixing your expression with !"default value", or simply ! if you want to have no default:

    <#assign map1 = { "1": "Potato", "2": "Chilly" } >
    <#assign map2 = { "1": "Apple", "2": "Plum", "3": "Extra" } >
    <#list (map1 + map2)?keys as key>
    <tr>
        <td>${key}</td>
        <td>${map1[key]!}</td>
        <td>${map2[key]!}</td>
    </tr>
    </#list>
    

    See also: