'Iterate over a YAML object using Jinja template

I have a yaml file with the following contents in it

interfaces:
   'loopback:local':
        -address: 0.0.0.0
         prefix: 24
         area: 192.168.1.2
         grp: testint
         intname: global
        -address: 0.0.0.0
         prefix: 24
         area: 192.168.1.3
         grp: prodint
         intname: global2

My jinja template looks like this

{% for intf in interfaces %}
  {{ intf }}

  {% for key,value in intf.items() %}
       {{ key }}
       {{ value }}
  {% endfor %}
{% endfor %}

When I try to access the elements from the object, I get an error saying no elements found



Solution 1:[1]

If your data is in an array arr, there are a couple of ways:

  1. Just do arr[0].map(...) (if your data looks like in your example)
  2. Use flatMap. If there is nesting like [ [ obj1, obj2 ], [ obj3, obj4 ] ] flatMap turns it to [obj1, obj2, obj3, obj4]

Example:

arr.flatMap(_ => _)

Edit: As others have mentioned, flat works just as well. It depends whether you want to perform some operations within the flatMap also, or to get an array of only the data1 properties of the objects in your example:

arr.flatMap(el => el["data1"]) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1