在freemarker中为散列内的散列分配键

时间:2015-04-24 15:31:06

标签: hash freemarker

我想在freemarker中创建一个现有模型的新模型,以便于使用。

我的模型是这样的:

[
    {
        "id": "1",
        "type": "TYPE_1",
        "code": "CODE_OF_TYPE_1"
    },
    {
        "id": "2",
        "type": "TYPE_1",
        "code": "ANOTHER_CODE_OF_TYPE_1"
    },
    {
        "id": "3",
        "type": "TYPE_2",
        "code": "CODE_OF_TYPE_2"
    },
    {
        "id": "4",
        "type": "TYPE_2",
        "code": "ANOTHER_CODE_OF_TYPE_2"
    }
]

我想做到这样:

 {
    "TYPE_1": {
        "CODE_OF_TYPE_1": "1",
        "ANOTHER_CODE_OF_TYPE_1": "2"
    },
    "TYPE_2": {
        "CODE_OF_TYPE_2": "3",
        "ANOTHER_CODE_OF_TYPE_2": "4"
    }
}

您可能知道,在freemarker中为哈希分配密钥有点奇怪..

我做的是:

<#assign preferencesByCode = {} />

<#list preferences as preference>
    <assign preferencesByCode = preferencesByCode + {preference.type : { preference.code: preference.id } } />
</#list>

但是这样做,它只保留最后一个id,所以我只有一种类型..

然后我尝试了这个:

<#if !(preferencesByCode[preference.type])??>
    <#assign preferencesByCode = preferencesByCode + {preference.type : { } } />
</#if>

<#assign subHash = preferencesByCode[preference.type] />
<#assign subHash = subHash + {preference.code : preference.id } />

但是subHash不作为参考保留,所以任何东西都被归为类型..

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

虽然我同意@ ddekany的评论,但这是解决问题的方法。

<#function filterList list type>
  <#local result={}>
  <#list list as preference>
    <#if preference.type == type>
      <#local result=result + {
        preference.code: preference.id
      }>
    </#if>
  </#list>
  <#return result>
</#function>

<#function convertList list>
  <#local result={}>
  <#list list as preference>
    <#if !result[preference.type]??>
      <#local result=result + { preference.type: filterList(list, preference.type) }>
    </#if>
  </#list>
  <#return result>
</#function>

<#assign transformedModel=convertList(model)>

答案 1 :(得分:0)

自由标记函数返回某些rootpath对象的最后一个哈希值

<#function deepHash obj path>
    <#assign hashes = path?split(".")>
    <#assign value = obj/>
    <#list hashes as hash>
        <#assign value = value[hash]!/>
    </#list>
    <#if value?is_boolean>
        <#return value?c>
    <#else>
        <#return value>
    </#if>
</#function>

例如:如果对象是

item 
    {
    "some": 
            {
        "thing": 
            {
                "deep": "Gotta",
            }
        }
    }


<#assign value = deepHash(item, "some.thing.deep") />
${value}

将显示:

Gotta