Filter / Organize array into key, value pairs for twig
Some twig stuff that I found to organize into key, value pairs.
January 17, 2022 • Code
{% 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: