2017-02-20 42 views
0

Im循环访问某些集合(在Shopify Liquid中称为类别),我需要将所有这些集合转换为数组,因此我可以访问它们的索引。将多个对象投射到一个数组

什么IM现在做的是这样的:

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

如何将这些对象集合转换为数组l我已经展示了下面的图片?

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

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

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

我得到这个: enter image description here

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

+0

大概是这样的'Object.values(集合)' –

+0

不,刚刚转一个Object中的所有值到一个数组。我需要将所有父对象的“对象”转换为数组。 – David

回答

2

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

<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 %} 
0

不知道你想达到什么,但看看Array.of方法。

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

不过 - 它看起来像你的收藏实际上是一个收集和你,所以你可能希望在定义的更高范围的数组,只是推/ CONCAT在一起,一旦你与你收集到你的代码。

+0

是的,即时通讯寻找所有这些对象,并将它们组成一个数组:我做了你所说的并像这样添加Array.of():console.log(Array.of(collections));这给了我在编辑部分上面提供的结果: – David

+0

是的,就像我之前说过的那样 - 使用推入到更高范围中定义的数组中。 @hymnz为你提供了一个例子。 –

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> 
相关问题