How to append a variable inside another vaiable name in liquid html

Here is the code:

{% for i in (0..5) %}
  {% assign product = recommendations.top_related_products_{{i}}.products[0].title %}
  {{ product }}
{% endfor %}

This code throws the error Liquid error: Cannot read property '0' of null

I have 6 arrays under recommendation like top_related_products_0...5.

How do I print the title variable which is inside the top_related_products_0..5?


Create a string containing the variable name, then use square bracket notation to access it.

For example:

{% for i in (0..5) %}
  {% capture related_products %}top_related_products_{{i}}{% endcapture %}
  {{ recommendations[related_products].products.first.title }}
{% endfor %}
js interview questions