how to write for each loop in jsonata
- User
how to write for each loop in jsonata
- Assistant
In JSONata, the
for eachloop can be written using themapfunction. Themapfunction transforms each item in an array by applying a given expression.Here is the syntax for writing a
for eachloop usingmapin JSONata:array_expression ~> [$expression]In the above syntax:
array_expressionis the expression that returns the array to iterate over.expressionis the expression to be applied on each item of the array.
For example, let's say you have an array of numbers
[1, 2, 3, 4]and you want to double each number. You can write thefor eachloop in JSONata like this:[1, 2, 3, 4] ~> $ * 2The above expression will return the array
[2, 4, 6, 8].You can also use the
mapfunction with more complex expressions and filter conditions. Here is an example where you only double the numbers that are greater than 2:[1, 2, 3, 4] ~> $[>2] * 2The above expression will return the array
[6, 8]since only the numbers3and4are greater than2and they are doubled.Note that the
~>operator is used to indicate that we want to apply themapfunction on the array.