Skip to content

Map Function

$map() transforms every element of an array into a new value. It is the JSONata equivalent of a for-each that produces a new array.


Syntax

$map(array, function($value, $index, $array) { ... })
  • array — the input array to transform
  • The function receives each element as $value
  • $index and $array are optional — leave them out if not needed

Basic example

$map([1, 2, 3], function($v) { $v * 2 })
/* [2, 4, 6] */

Transforming objects

A common use in production rules is reshaping a distinct list of values into objects for display:

(
  $data := $distinct($[type = "FamilyInstance"].values.assemblyCode);

  $map($data, function($v) {
    {
      "assemblyCode": $v,
      "count": $count($[type = "FamilyInstance" and values.assemblyCode = $v])
    }
  })
)

This produces one summary object per distinct assembly code with a count of matching instances.


When to use $map() vs .{ }

Both $map() and the .{ } projection can produce arrays of objects.

$map() .{ } projection
Input Any array, including variables Array from a filter
Index access Yes ($index) No
Extra context Can reference outer variables Shares outer scope
Readability More explicit More concise

Use .{ } when transforming a filter result directly. Use $map() when working with a variable that holds an array, or when you need the index.


$map() with $distinct()

$distinct() removes duplicate values from an array. Combined with $map(), it is useful for building per-value summaries:

(
  $assemblyCodeIncluded := /^(11\.\d\d)$/;

  $codes := $distinct(
    $[type = "FamilySymbol"
      and $string(values.assemblyCode) ~> $assemblyCodeIncluded
    ].values.assemblyCode
  );

  $map($codes, function($v) {
    { "assemblyCode": $v }
  })
)

Common mistakes

  • Calling $map() on a value that might not be an array — if the input is a single object or undefined, $map() returns undefined. Wrap the input in [...] if needed
  • Using $map() where .{ } would be cleaner — $map() adds complexity when a simple projection suffices