2014-01-10 80 views
2
我有在通過JSON使用dust.js循環麻煩

循環,這是我的JSON灰塵通過JS對象的JSON

{ 
    "Undergraduate":{ 
     "metaid":"0770", 
     "Offcampus":{ 
     "FeesItems":{ 
      "tuition":{ 
       "label":"Tuition Fees", 
       "value":"5,870" 
      }, 
      "comprehensive":{ 
       "label":"Comprehensive Fees", 
       "value":"2,141" 
      }, 
      "studentActivity":{ 
       "label":"Student Activity Fees", 
       "value":"190" 
      }, 
      "academicExcellence":{ 
       "label":"Academic Excellence Fee", 
       "value":"225" 
      }, 
      "room":{ 
       "label":"Room", 
       "value":"0" 
      }, 
      "board":{ 
       "label":"Board", 
       "value":"0" 
      }, 
      "livingAllowance":{ 
       "label":"Living Allowance", 
       "value":"9,738" 
      } 
     } 
     } 
    } 
} 

我想通過項目環內FeesItems對象..

{#Undergradaute.Offcampus.FeesItems} 
    {label}, {value}{~n} <!-- What should be given in this line? --> 
{/Undergradaute.Offcampus.FeesItems} 

回答

3

FeesItems渲染從JSON labelvalue只要FeesItems通過項這將循環是一個數組FeesItems= []

http://akdubya.github.io/dustjs/#guide

{ 
    "Undergraduate":{ 
     "metaid":"0770", 
     "Offcampus":{ 
     "FeesItems":[{ 
       "label":"Tuition Fees", 
       "value":"5,870" 
      }, 
      { 
       "label":"Comprehensive Fees", 
       "value":"2,141" 
      }, 
      ... 
] 
     } 
     } 
    } 
} 

這裏是集塵引導樣本:

{#friends} 
    {name}, {age}{~n} 
{/friends} 

{ 
    friends: [ 
    { name: "Moe", age: 37 }, 
    { name: "Larry", age: 39 }, 
    { name: "Curly", age: 35 } 
    ] 
} 

更新1:

既然你的願望不會改變原來的JSON,你需要生成一個來自原始JSON的新對象類似於

var newModel = Object.keys(obj.Undergraduate.Offcampus.FeesItems).map(function(prop){ return obj.Undergraduate.Offcampus.FeesItems[prop] }); 

請注意,JavaScript的參考保持的對象,如果嘗試一些類似:

originalObj.Undergraduate.Offcampus.FeesItems.board.label = "Costa Rica" 
console.log(newModel[5].label); 
+0

我不能修改實際的JSON,是有沒有辦法做到不改變json?如果不是dust.js,還有其他的模板如鬍子,把手? – NEO

+1

@NarendranSankaran我用你的問題的解決方案更新了郵政。希望它有幫助 – Dalorzo

+0

有沒有辦法通過'key'關鍵字引用對象鍵?這是我的問題http://stackoverflow.com/questions/29554132/does-dust-js-provide-a-way-to-reference-an-object-key-value-by-keywords-key-an – Green

0

可以遍歷使用輔助的對象。

例如,你可以定義這樣一個幫手:

dust.helpers.iter = function(chunk, context, bodies, params) { 
    var obj = dust.helpers.tap(params.obj, chunk, context); 

    var iterable = []; 

    for (var key in obj) { 
    if (obj.hasOwnProperty(key)) { 
     var value = obj[key]; 

     iterable.push({ 
     '$key': key, 
     '$value': value, 
     '$type': typeof value 
     }); 
    } 
    } 

    return chunk.section(iterable, context, bodies); 
}; 

然後,在你的模板,你會遍歷這樣的:

{@iter obj=Undergradaute.Offcampus.FeesItems} 
    {$value.label}, {$value.value}{~n} 
{/iter}