Filter / Organize array into key, value pairs for twig

Twig may be slightly tricky in handling data. I documented how to organize and filter array into key, value pairs for twig.

January 18, 2022

Code 💻

1 min read

{% set locations = {} %}

{% for location in locationList.locations.all() %}
  {# create a dynamic property if one doesn't exist #}
  {% if not attribute(locations, location.locationState) is defined %}
      {% set locations = locations|merge({ (location.locationState) : [location] }) %}

  {# else update the dynamic property with the new title #}
  {% else %}
      {% set arr = attribute(locations, location.locationState) %}
      {% set arr = arr|merge([location]) %}
      {% set locations = locations|merge({ (location.locationState) : arr }) %}

  {% endif %}
{% endfor %}

{{ dump(locations) }}

Source: Stack Exchange

Invely's