How to turn a string in to an array of objects with keys and values in Liquid

Viewed 3802

I'm looking to turn a string that you can be edited in Shopify theme settings into an array of object key values in my Liquid file.

For example:

var text = 'key1:value1,key2:value2,anotherKey:anotherValue'

in to:

var array = [{key1: value1}, {key2: value2}, {anotherKey: anotherValue}]

Each object will be separated by a ',' in the string and the key will be to the left of a ':' with the value to the right.

I need to write this inside a theme.liquid file but unsure how to achieve this. Any help would be most appreciated.

I've so far only got as far as:

{% assign text = 'key1:value1,key2:value2,anotherKey:anotherValue' %}

{% assign splitText = text | split: ',' %}

{% assign array = '' | split: '' %}
{% for data in splitText %}
    {% assign key = data | split: ':' | first %}
    {% assign value = data | split: ':' | last %}
    {% assign array = array | concat: key | append: ':' | concat: value %}
{% endfor %}

{{ array }}

1 Answers

Creating associative arrays or arrays with named indexes is not possible in Liquid. However, as a work around, you can create 2 arrays. Treat the same indexes of one array as key while other as value.

A sample implementation would look like

{% assign text = 'key1:value1,key2:value2,anotherKey:anotherValue' %}

{% assign objArr = text | split: ',' %}

{% assign keyArr = ''%}
{% assign valArr = ''%}


{% for obj in objArr %}
    {% assign key = obj | split: ':' | first %}
    {% assign value = obj | split: ':' | last %}
    {% assign keyArr = keyArr| append: ',' | append: key  %}
    {% assign valArr = valArr| append: ',' | append: value  %}
{% endfor %}

{% assign keyArr = keyArr | remove_first: ',' | split: ',' %}
{% assign valArr = valArr | remove_first: ',' | split: ',' %}


{% for obj in objArr %}
    {{keyArr[forloop.index0]}} :  {{valArr[forloop.index0]}}
    <br/>
{% endfor %}

The above code does a basic job. Do not forget to compare both array lengths to identify if all key value pairs were created perfectly as per logic.

Related