2016-08-02 96 views
0

我有集合是這樣的:流星火焰顯示陣列

enter image description here

欲遍歷例如object.questions.teema。

我有幫助:

Template.game.helpers({ 
    theGame: function() { 
     var theGame = Game.findOne({_id:"LhQmaZKW8eJNenyX9"}) 
     console.log(theGame) 
     return theGame 
    } 
}); 

和模板:

<template name="game"> 

{{#with theGame}} 
    {{#each theGame.questions}} 
    {{teema}} 
    {{/each}} 
{{/with}} 
</template> 

但它不工作,什麼是錯的模板?

回答

0

「#each theGame.questions」不會的#with內工作,因爲你可以直接訪問「theGame」對象。

問題是,當你嘗試在#with中獲取遊戲對象時,它會返回你未定義的,因爲'theGame'對象沒有theGame屬性,你想在#with塊中訪問它。

<template name="game"> 
    {{#with theGame}} 
    {{#each questions}} 
     //Thie #each because you have nested array. As I can see in your console log. 
     {{#each this}} 
     {{teema}} 
     {{/each}} 
    {{/each}} 
    {{/with}} 
</template> 
0

theGame.questions是具有teema鍵的對象數組的數組(可迭代)。因此,您仍然需要迭代第二級數組,或者在最終使用teema屬性最終到達對象之前定義該數組中的特定項目。

也許是這樣的:

{{#with theGame}} 
    {{#each questions}} 
    {{#each this}} 
     {{this.teema}} 
    {{/each}} 
    {{/each}} 
{{/with}} 

但要看你爲什麼擺在首位,這些2級陣列。

+0

因此,像這樣: {{#with theGame}} {{#each theGame.questions}} {{#each questions.teema}} {{TEEMA}} {{/每個}} {{/每個}} {{帶}} 這似乎並不工作 – Villemh

+0

沒有。用暫定代碼編輯答案。首先檢查你爲什麼需要這些2級陣列... – ghybs

+0

這是個好建議,我不需要2級陣列。謝謝。 – Villemh

0

什麼是{{teema}}應該是?

無論如何,您可以從console.log語句中看到{{theGame.questions}}返回另一個數組。但該數組返回對象。這對於Blaze來說非常難以查詢。

更好的解決辦法是將壓平,使您的數據的形狀是這樣的:

questions: [ 
    { 
     a: 'asdfkjah', 
     level: 'askdjfhal', 
     q: 'asdkfh', 
     teema: 'asdkfjh' 
     vaartus: 100 
    }, 
    { 
     ... 
    } 
] 

這樣你就不必嵌套在一個數組的數組。這將允許您:

{{#with theGame}} 
    {{#each theGame.questions}} 
    {{this.teema}} 
    {{/each}} 
{{/with}}