1

I have an array of hashes:

a = [{a:"ahmed", b: "gaber"}, {a: "biga", b: "gaber"}]

I want to map the array into a comma separated string with each separated part being the concatenation of the values of a hash. In ruby, this would be written:

a.map {|o| o[:a] + o[:b] }.join(",")

How can I write this in Liquid?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • You can format code with 4 leading spaces. Can you check what you posted? I have the impression there is some cut+paste waste from another post (the part with up vote...) – knut Nov 15 '15 at 19:48
  • I copied it from old question I wrote it then deleted, sorry I didn't note that. – Ahmed Gaber - Biga Nov 16 '15 at 12:33

2 Answers2

2

If you're writing directly to the output, you could use a for tag, e.g.:

{% for item in items %}{% if forloop.first == false %},{% endif %}{{ item.a }} {{ item.b }}{% endfor %}

==> "ahmed gaber,biga gaber"

But if you're trying to assign to a variable, I don't think there's a way to do that purely in liquid because there's no filter that is the equivalent to the ruby map function. The closest I can think of is to preprocess the list so it looks like this:

a = [{a:"ahmed", b: "gaber", c: "ahmed gaber"}, 
     {a: "biga", b: "gaber", c: "biga gaber"}]

and then use liquid map to pluck the "c" field from each hash:

{{ assign csv = items | map: "c" | join: ","}}
The result is: {{ csv }}

==> "ahmed gaber,biga gaber"
mikebridge
  • 4,209
  • 2
  • 40
  • 50
1

Liquid has a map filter for arrays, but it only lets you access one attribute from each object in your array: https://docs.shopify.com/themes/liquid-documentation/filters/array-filters#map

There is a pretty thorough answer on iterating through hashes in Liquid here: Iterate over hashes in liquid templates

Using the above answer as a template, you could iterate (and present) your data in the way you specified with these tags:

{% for name in a %}
    {{ name.a }} {{ name.b }}{% unless forloop.last %},{% endunless %}
{% endfor %}

One other piece to this markup is the use of the forloop variable from inside the loop. With this we can place a comma unless we're at the last entry in the array.

More on liquid forloops (and pretty much everything else liquid) here: https://github.com/Shopify/liquid/wiki/Liquid-for-Designers

Community
  • 1
  • 1
Naomi
  • 61
  • 1