Skip to content Skip to sidebar Skip to footer

How To Update A Value In Array Scoped Variable?

I have a scoped variable that stores an archive: viewScope.MY_SCOPE = new Array(); viewScope.MY_SCOPE.push(['id0', 0, true]); viewScope.MY_SCOPE.push(['id1', 1, false]); viewScope.

Solution 1:

When adding the SSJS array object to the scope, it is converted to a java.util.Vector. Hence, if you want to set the value, you should use

viewScope.MY_SCOPE[1].set(2,"true");

instead of viewScope.MY_SCOPE[1][2] = "true";.

I think the problem is that using ...[2] = "true" tries to execute the put method of the given object. While put is available in Maps like HashMaps or the scope maps, Vectors use set instead of put to change values. For that reason, you get the "action expression put(...) not supported" error. In contrast to this, it's no problem to get the variable with viewScope.MY_SCOPE[1][2] because the get method is availiable in both HashMaps and Vectors.


Solution 2:

When storing arrays in scope variables, I like to put the value into a properly typed javascript variable, make edits, and then replace the scope variable with the updated value.

In your case I would do the following:

var tempVar = viewScope.MY_SCOPE.toArray();  //convert to array to make sure properly typed
tempVar[1][2] = true;
viewScope.put(MY_SCOPE,tempVar);

Update: After testing your code along with mine, I too get the same error. To be honest, I never would have messed with multi dimensional arrays in the first place. This is a perfect opportunity to use an array of objects:

var tempVar = [];  // initialize the array

tempVar.push({val1:"id0",val2:0,val3:true});
tempVar.push({val1:"id1",val2:1,val3:false});
tempVar.push({val1:"id2",val2:3,val3:true});
viewScope.put("MY_SCOPE",tempVar);

Then to change the desired value:

var tempVar = [];
tempVar = viewScope.get("MY_SCOPE");
tempVar[1].val3 = true;
viewScope.put("MY_SCOPE",tempVar)

I tested this method and it works fine.


Post a Comment for "How To Update A Value In Array Scoped Variable?"