2

I would like to remove a certain element from an array in Velocity Template Language. I did not find any appropriate method looking through the documentation of Apache VTL, that's why I am asking here for help. I have tried following (.remove() doesn't seem to be a method on array items):

#set($linkedWIARRAY = ["ABC-123, DEF-345, GHI-678"])

#set($dummy=$linkedWIARRAY.add("JKL-901"))

#set($dummy = $linkedWIARRAY.remove("DEF-345"))

$linkedWIARRAY

$linkedWIARRAY returns [ABC-123, DEF-345, GHI-678, JKL-901], showing that remove very likely doesn't exist as method on arrays ;)

There is a similar question on SO, that didn't help me: velocity template drop element from array

SteffPoint
  • 479
  • 2
  • 9
  • 24

1 Answers1

3

The problem lies in the initialization of the list. It should be:

#set($linkedWIARRAY = ["ABC-123", "DEF-345", "GHI-678"])

that is, each string should be enclosed in double quotes, not the whole string.

Claude Brisson
  • 4,085
  • 1
  • 22
  • 30
  • May I address one more question to you? :) How can I initialize an empty arraylist in such way, that values added to this arraylist are "embedded" within`""` -> `"vaue","value"`. When I use `#set($linkedWIARRAY = [])` and then add values to it like `#set($dummy = $linkedWIARRAY.add("${linkedWILevel1.getId}"))`, then the arraylist returned looks like: `[ABC-123, DEF-345]` – SteffPoint Oct 01 '20 at 06:29
  • 1
    @SteffPoint You should first ask yourself the question of whether you want the quotes to be in the array, or the quotes to be added around array values at the moment they are displayed. The second option looks more natural to me, hence you should display yourself the array elements, adding quotes around it... And if you do all that to be able to format JSON, don't use an array list, that's awkward, use some Json tool in your context which will properly format the output. There are plenty around. – Claude Brisson Oct 01 '20 at 07:36