Multi-Dimensional and Associative Arrays in Shopify Liquid

You’re here because you’re sure you’re missing something. You can’t figure out how to create multi-dimensional and associative arrays in Shopify.

Sadly, you’re not missing something. In fact, while you can access multi-dimensional arrays just fine, you can’t assign values to them. Similarly you can access objects with named members that have values and even iterate through them just like associative arrays, but you can’t create such a thing.

All is not lost.

You can actually work around the lack of associative and multi-dimensional arrays in Shopify with a bit of gymanstics and a fair bit of code bloat. To be fair, Liquid is a templating language, like Twig or Smarty, and you’ll be less frustrated if you think of it as smart HTML rather than dumb Ruby.

So how do you do it?

It’s fairly simple actually.

All you need to do is create multiple parallel arrays so that element 11 of array A corresponds to element 11 of array B, iterate through until you find the value you need in array A and then use the array index to grab the corresponding value in array B.

How do you create arrays in Liquid?

I’m guessing that if you have found this page, you’ve already figured out how to create a basic, one-dimensional array in Shopify. Essentially, you create a string with a delimiter and then you split the string to create your array.

Yup, it’s a hassle, but it works. You basically have a two-dimensional associative array, but instead of letting Liquid do the heavy lifting for you, you have to do it yourself.

This can get really complicated and without more powerful data structures, you’re condemned to lots of relatively hard-to-follow code to achieve some very simple things, but there it is. I just used this technique to map menu items in a hierarchical menu. It wasn’t pretty, but it worked. But that’s for a future post.