将多个对象转换为数组

时间:2017-02-20 20:40:32

标签: javascript arrays collections shopify liquid

我循环浏览一些集合(在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>

这是我得到的结果:

enter image description here

我需要在数组中得到这样的结果: enter image description here enter image description here

如何将这些对象组转换为数组,就像我为下面的图像所示?

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

当我使用Array.of()时,如下所示:

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

我明白了: enter image description here

但是所有这些对象仍然不在数组中。也许把它提升一个级别?

3 个答案:

答案 0 :(得分:2)

为什么要在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 %}

答案 1 :(得分:0)

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

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

尽管如此 - 看起来你的系列实际上是一个集合,因此你可能会在更高的范围内找到一个数组,只要你的代码到达你的代码就可以将它们连接在一起。

答案 2 :(得分:0)

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

<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>