map
Apply a transformation to all the elements of an array
Definition
array[any] map(expression->any $expression, array[any] $array)
Applies $expression
to each of the elements in $array
and return the array of results. An input $array
of length N
will produce an output array of length N
.
Parameters
expression -> any $expression
Expression to apply to the elements of $array
.
array[any] $array
The array whose elements are going to be transformed by $expression
.
Returns
array[any]
Input $array
after its elements have been transformed by $expression
.
Examples
{
a: map(&name, `[{"name": "Jane"}, {"name": "John"}, {}, [], {"name": "Julia"}]`), // Identifier
b: map(&[], `[[1, 2, 3, [4]], [5, 6, 7, [8, 9]]]`), // Flatten operator
c: map(length(@), `[[1, 2, 3, [4]], [5, 6, 7, [8, 9]]]`) // Length function
}
{
"a":["Jane","John",null,null,"Julia"],
"b":[[1,2,3,4],[5,6,7,8,9]],
"c":[4,4]
}
Remarks
In the earlier example, a warning is raised because the identifier expression name
couldn't be found in some of the elements, namely, {}
is an empty object and []
is not even an object. The warning doesn't halt the execution of the program, but merely informs the user.
It can be helpful to think of this function as moving between all the elements in the array and acting on them with $expression
. In other words, $map
changes scope to each of the elements of $array
in turn. This means that the current node operator @
is often useful in combination with map
, because it allows access to the entire element for functions that might require it, like the example at c
above.
Unlike a wildcard expression array[*].property
, map(&property, array)
will include the result of applying $expression
for every element in $array
, even if the result is null
.
Updated about 1 year ago