How to Remove comma for the last object in nested for loop?

719 views Asked by At

I want to remove the comma from the last object in nested for loop:

[{% for item1 in articles.results.entities %}
    {% for item2 in articles1.results.entities %}
        {% if item1.knowledgearticleid != item2.knowledgearticleid %}
            {
            "Id":"{{item1.knowledgearticleid}}",
            "Title":"{{item1.title}}",
            "Articlepublicumber":"{{item1.articlepublicnumber}}",
            "Description":"{{item1.description}}"            
            }
           
        {% endif %}       
       
    {% endfor %}
    {% unless forloop.last %},{% endunless %}
{% endfor %}]

But this is not working; it is giving me duplicate commas:

[
  {
    "Id": "ddcb41c6-1f33-ea11-a813-000d3a3be5cf",
    "Title": "1 Test1",
    "Articlepublicumber": "KA-01992",
    "Description": "Test1"
  },,
  {
    "Id": "9564dc21-9df6-414b-ab99-da4ba534fd83",
    "Title": "Test2",
    "Articlepublicumber": "KA-03363",
    "Description": "Test2"
  }
]
1

There are 1 answers

0
Arun Vinoth-Precog Tech - MVP On

Identical issue in terms of Shopify liquid snippet discussed here and this is common scenario with concatenation in any language.

With each accepted iteration, add a comma and then the “needed item”.  Except if this is the first accepted iteration, don't add the comma.

I just manage to modify your code, but test it on your end. But you got the idea right?

[{% assign list_items = "" %}
  {% for item1 in articles.results.entities %}
    {% for item2 in articles1.results.entities %}
        {% if item1.knowledgearticleid != item2.knowledgearticleid %}

         {% unless list_items == "" %}

          {% assign list_items = "zzz" %}

            {
            "Id":"{{item1.knowledgearticleid}}",
            "Title":"{{item1.title}}",
            "Articlepublicumber":"{{item1.articlepublicnumber}}",
            "Description":"{{item1.description}}"            
            }
          {% endunless %}

          {% unless list_items == "zzz" %}

            ,{
            "Id":"{{item1.knowledgearticleid}}",
            "Title":"{{item1.title}}",
            "Articlepublicumber":"{{item1.articlepublicnumber}}",
            "Description":"{{item1.description}}"            
            }
          {% endunless %}

        {% endif %}       
       
    {% endfor %}

{% endfor %}]