map

The map filter lets you apply an arrow function to each item in an array or object to return a new value. 

The function can either output content, or you can return a value to a variable. If you return a value the new variable value will be an array.

The map filter applies an arrow function to the elements of a sequence or a mapping. The arrow function receives the value of the sequence or mapping

{% set categoryIds = post.categories|map(category => category.id) %}

Arguments

The arrow function for the map filter can receive one or two parameters. The first parameter is the array or object value. The second optional parameter is the index key.

value

The value of the array or object at this step of the iteration.

key

The array index number or object key value at this step of the iteration.

Examples

Output vales from an array

In this example we have an array of names. Each name is an object. Our arrow function uses just the array value and outputs the first and last name.

{% set names = [
    {first: "Joe", last: "Douglas"},
    {first: "Susan", last: "Smith"},
] %}

{{ names|map(name => "#{name.first} #{name.last}")|join(', ') }}
{# outputs Joe Douglas, Susan Smith #}

The above example uses string interpolation to output the values. Alternately you could use the ~ operator to join strings together. The result is the same.

{% set names = [
    {first: "Joe", last: "Douglas"},
    {first: "Susan", last: "Smith"},
] %}

{{ names|map(name => name.first ~ ' ' ~ name.last)|join(', ') }}
{# outputs Joe Douglas, Susan Smith #}

Set values in a new variable

In addition to outputting values you can also set new values to an array.

In this example we're going to get the category names for a blog post. The post.categories array holds information for each category that a blog post is assigned to. Each category in the array is an object of information. In this example we only want to use the category name.

{% set categoryNames = post.categories|map(category => category.name) %}

Access the object key

If your data is an object then you can access the object keys as the second argument for the arrow function.

{% set fruitColors = {
    "apple": "red",
    "orange": "orange",
    "banana": "yellow"
} %}

<p>{{ fruitColors|map((color, fruit) => "#{fruit|capitalize} is #{color}")|join('<br>') }}</p>

# This outputs
# <p>Apple is red<br>
# Orange is orange<br>
# Banana is yellow<br>
# </p>

The arrow function also has access to the current context at _context.

This documentation is only for Aptuitiv CMS. Learn more.
Get Started With Aptuitiv