2013-08-04 26 views
0

我需要將(json)對象插入到頁面中使用的數組中。我用jade使用nodejs,並假設下面的代碼可能符合我的目的,但它不起作用。在頁面腳本中使用玉的迭代

//this code is in the template: 
    script. 
     otherPlayers = {}; 
     each player in playerList 
      otherPlayers["#{player.playerId}"] = !{JSON.stringify(#{player})}; 

在頁面預期的結果是:

<script> 
    otherPlayers = {}; 
    otherPlayers[0] = {"playerId": 0, "playerName": "Leo" }; 
    otherPlayers[1] = {"playerId": 1, "playerName": "Daniel" }; 
    otherPlayers[2] = {"playerId": 2, "playerName": "Lucas" }; 
</script> 

任何暗示被廣泛接受。 在此先感謝。

回答

2

您可以在模板文件中進行如下操作。

//In the template file 
script. 
    otherPlayers = {}; 
    var cplayerList = !{JSON.stringify(playerList)}; 
    for(player in cplayerList) { 
     otherPlayers[cplayerList[player].playerId] = cplayerList[player]; 
    } 
    console.log(otherPlayers); 
+0

感謝它的工作原理 – NodeJsBeginner