2017-02-20 103 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>