Search code examples
arraysjsonxpagesxpages-ssjs

SSJS remove item from an array


In ssjs I have an array that contains jsonobjects. this array is stored in a scope variable and displayed in a repeat control:

<xp:repeat id="rptAssessors" value="#{sessionScope.tmpAssessors}" var="obj" indexVar="idx">

From the repeat control I would like to add the option to remove individual items from the array e.g. via onclick event on a button for each row:

<xp:eventHandler event="onclick" submit="true" refreshMode="partial" immediate="true" refreshId="dlgContent"> <xp:this.action> <xp:executeScript
 script="#{javascript:removeAssessor(idx);}"> </xp:executeScript> </xp:this.action></xp:eventHandler>   

My removeAssessor function looks as followed:

function removeAssessor(idx){   

    var jsonObjArr = sessionScope.get("tmpAssessors");

    print("before elements " + jsonObjArr.length)
    print(idx + 1)
    jsonObjArr.splice(idx,1);
    print("after elements " + jsonObjArr.length)

    sessionScope.put("tmpAssessors",jsonObjArr);

}

I notice the splice() method does not work. I read on an xsnippet that this method does not work in SSJS and an alternative is posted as an xsnippet but this is for arrays containing strings

https://openntf.org/XSnippets.nsf/snippet.xsp?id=remove-an-entry-from-an-array-of-strings

Anyone can tell me how to remove an item from the array that is not a string?


Solution

  • Array.splice does work in SSJS, but not in the "inline way" you might be used to from CSJS: In CSJS the modification is done inline (no new array is created) and the removed elements are returned. In SSJS, the original array is not modified and the return value is a copy of the array excluding the spliced elements.

    If you replace jsonObjArr.splice(idx,1); with jsonObjArr=jsonObjArr.splice(idx,1); your code should work fine.