Search code examples
xpagesxpages-ssjs

how to read an entry in a hashmap from SSJS?


I have in a viewScope a hashmap stored but how can I read an entry from it e.g. from a computed text in SSJS ?

var pm = viewScope.get("person");
var entry = pm.entrySet(); 
return entry.getValue("email")

Solution

  • entrySet() is a way for you to iterate your Map. For example:

    Map<String, String> m = new HashMap<String, String>();
    m.put("one", "1");
    m.put("two", "2");
    
    for (Map.Entry<String, String> entry : m.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    

    will print:

    one=1
    two=2
    

    If you want to read a specific key from a map it's actually very simple:

    <xp:text value="#{viewScope.person.email}" />
    

    or if you need dynamic (where you would replace the literal value expressed with the quotes with another dynamic variable of your choosing):

    <xp:text value="#{viewScope.person['email']}" />