[英]Separating each different Javascript property within object within array
我已經為此困擾了一段時間。 基本上,我有一個對象數組(目前僅關注“ 00”對象),並且我希望將bestScore屬性組合在一起,如下所示:
..
用戶組
蘋果
..
用戶組
香蕉,
楊桃
..
用戶組
番茄
..
這是我到目前為止的代碼。。。我是新手,所以有點困惑。
var playerBatch = new Array();
playerBatch["00"] =
[
{userName: "apple", bestScore: "10"}
{userName: "banana", bestScore: "20"}
{userName: "starfruit", bestScore: "20"}
{userName: "tomato", bestScore: "30"}
];
var batch = "00";
for (i=0; i < playerBatch[batch].length; i++) {
if (playerBatch[batch][i].bestScore == "10") {
document.write("User Group")
document.write(playerBatch[batch][i].userName)
}
};
如果有人對如何解決這個問題有任何想法,我將不勝感激。
謝謝。
編輯:看起來您在示例中缺少的是playerBatch["00"]
的對象之間的逗號。 在您進入分類工作之前,這將破壞整個過程。
為了對多個結果進行分組,您需要在調用document.write()
之前緩存/存儲所有匹配項(可能在本地范圍的數組中document.write()
。
…如果bestScore
列出所有組,則必須遍歷數組以構建可能的bestScore
值的列表(數組), 然后使用已編寫的代碼遍歷該組。
就是說,您可能希望對正在寫到文檔中的(輸出)字符串進行處理,以在“用戶組”和結果匹配項之間添加空格,控制換行符或換行帶有語義HTML。 根據完成布局的復雜程度,您可能會受益於使用諸如Handelbars甚至是Nano(模板)之類的模板庫。
var playerBatch = new Array(); playerBatch["00"] = [{ userName: "apple", bestScore: "10" }, { userName: "banana", bestScore: "20" }, { userName: "starfruit", bestScore: "20" }, { userName: "tomato", bestScore: "30" }]; var batch = "00", groupArray = []; for (i = 0; i < playerBatch[batch].length; i++) { if (playerBatch[batch][i].bestScore == "20") { groupArray.push(playerBatch[batch][i].userName) } }; if( groupArray.length ){ document.write( "User Group: " ); document.write( groupArray.join( ", " ) ); }
感謝Ito,這與在我的函數中使用UnderscoreJS的groupBy一起成功了! 我不確定如何正式“解決”這個問題,以便您獲得幫助,但我似乎已經准備就緒。
var playerBatch = new Array(); playerBatch["00"] = [{ userName: "apple", bestScore: "10" }, { userName: "banana", bestScore: "20" }, { userName: "starfruit", bestScore: "20" }, { userName: "tomato", bestScore: "30" }]; var batch = "00", groupArray = []; for (i = 0; i < playerBatch[batch].length; i++) { if (playerBatch[batch][i].bestScore == "20") { groupArray.push(playerBatch[batch][i].userName) } }; if( groupArray.length ){ document.write( "User Group: " ); document.write( groupArray.join( ", " ) ); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.