将多个对象投射到一个数组

Cast multiple Objects to an array

我正在遍历一些集合(在 Shopify Liquid 中称为类别),我需要将所有这些集合转换成一个数组,以便我可以访问它们的索引。

我现在正在做的是:

{% for link in linklists[page.handle].links limit:1 %}
 {% assign collection = link.object %}

 // Im doing the above code somewhere above in the liquid file, thats where I get the link.object


<script>
  var collections = {{ link.object | json }};
  console.log(collections);
</script>

这是我得到的结果:

我需要这样的结果,在一个数组中:

如何将这些对象集转换为数组,如下图所示?

/********** 编辑 *******/

当我使用 Array.of() 时,像这样:

console.log(Array.of(collections));

我明白了:

但是所有这些对象仍然不在数组中。也许将其提升一级?

不确定您要实现的目标,但请查看 Array.of 方法。

Array.of({obj1Prop1: 'value1'}, { obj2Prop1: 'value2'});

尽管如此 - 看起来您的集合实际上是一个集合,因此您可能会在定义的更高范围内寻找一个数组,一旦您到达您的集合代码就将它们推/连接在一起。

为什么要在 for 循环中启动 collections 变量?试试这个

<script>var collections = new Array</script>
{% for link in linklists[page.handle].links limit:1 %}
 {% assign collection = link.object %}

 // Im doing the above code somewhere above in the liquid file, thats where I get the link.object


<script>
  collections.push({{ link.object | json }});
  console.log(collections);
</script>
{% endfor %}

该对象在大多数情况下可能更有用,但您可以这样做:

<script>
  var collections = {

    "collections": [{% for collection in collections %}
      {
      {% if collection.image %}"image": "{{ collection.image }}",{% endif %}
      "body_html": "{{ collection.description | url_escape }}",
      "handle": "{{ collection.handle }}",
      "id": {{ collection.id }},
      "sort_order": "{{ collection.default_sort_by }}",
      "template_suffix": "{{ collection.template_suffix }}",
      "title": "{{ collection.title }}",
      "products_count": {{ collection.products_count }},
      "url": "{{ collection.url }}",
      "products": []
      }{% unless forloop.last %},{% endunless %}{% endfor %}
    ]
  }
</script>