I had a vanilla js script that initially appeared as follows:
const products = [
{
id: 1,
title: 't-shirt'
},
{
id: 2,
title: 't-shirt'
},
{
id: 3,
title: 'jeans'
}
]
My goal was to link similar products based on their titles. I achieved this by modifying the script like so:
products.forEach(product => {
product.linked_products =
products
.filter(linked_product => linked_product.id !== product.id && linked_product.title === product.title)
})
The functionality worked correctly, but there were issues with the implementation that required me to create a JSON API in Shopify. The issue I encountered involved handling trailing commas when trying to replicate the above code block using Liquid in a JSON format. This resulted in unexpected token errors due to the presence of trailing commas.
I identified that the if statement within the Liquid code was causing the trailing comma problem, and I am currently struggling to find a solution. My Liquid code is structured as follows:
{% layout none %}
{
"title": {{ collection.title | json }},
"description": {{ collection.description | json }},
"products": [
{% for product in collection.products %}
{
"title": {{ product.title | json }},
"linked_products": [
{% for linked_product in collection.products %}
{% if linked_product.id != product.id and linked_product.title == product.title %}
{
"title": {{ linked_product.title | json }},
"handle": {{ linked_product.handle | json }}
}{% unless forloop.last %},{% endunless %}
{% endif %}
{% endfor %}
]
}{% unless forloop.last %},{% endunless%}
{% endfor%}
]
}
The resulting output exhibits correct linked products but lacks proper comma placement.
{
"title": "Leggings",
"description": "",
"products": [
{
"title": "High waisted leggings",
"linked_products": [
{
"title": "High waisted leggings",
"handle": "high-waisted-leggings-1"
},
{
"title": "High waisted leggings",
"handle": "high-waisted-leggings"
}
]
},
{
"title": "Test",
"linked_products": [
{
"title": "Test",
"handle": "high-waisted-leggings-3"
},
]
},
{
"title": "Test",
"linked_products": [
{
"title": "Test",
"handle": "testb"
},
]
},
{
"title": "High waisted leggings",
"linked_products": [
{
"title": "High waisted leggings",
"handle": "high-waisted-leggings-2"
},
{
"title": "High waisted leggings",
"handle": "high-waisted-leggings"
}
]
},
{
"title": "High waisted leggings",
"linked_products": [
{
"title": "High waisted leggings",
"handle": "high-waisted-leggings-2"
},
{
"title": "High waisted leggings",
"handle": "high-waisted-leggings-1"
},
]
}
]
}
While the linked products are accurately displayed, the formatting issue with commas remains unresolved.