Reputation: 2001
I am having trouble in using dust.js to loop through a json, here is my 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"
}
}
}
}
}
I would like to loop through the items inside FeesItems object..
{#Undergradaute.Offcampus.FeesItems}
{label}, {value}{~n} <!-- What should be given in this line? -->
{/Undergradaute.Offcampus.FeesItems}
Upvotes: 2
Views: 5481
Reputation: 20014
This will loop through the items in FeesItems
rendering label
and value
from JSON as long as FeesItems is an array FeesItems= []
http://akdubya.github.io/dustjs/#guide
{
"Undergraduate":{
"metaid":"0770",
"Offcampus":{
"FeesItems":[{
"label":"Tuition Fees",
"value":"5,870"
},
{
"label":"Comprehensive Fees",
"value":"2,141"
},
...
]
}
}
}
}
Here is a sample of the Dust Guide:
{#friends}
{name}, {age}{~n}
{/friends}
{
friends: [
{ name: "Moe", age: 37 },
{ name: "Larry", age: 39 },
{ name: "Curly", age: 35 }
]
}
Update 1:
Since you desire not to change the original JSON you will need to generate a new Object from your original JSON Something like
var newModel = Object.keys(obj.Undergraduate.Offcampus.FeesItems).map(function(prop){ return obj.Undergraduate.Offcampus.FeesItems[prop] });
Please note that javascript will keep the reference to objects, if try something something like:
originalObj.Undergraduate.Offcampus.FeesItems.board.label = "Costa Rica"
console.log(newModel[5].label);
Upvotes: 4
Reputation:
You can iterate over an object using a helper.
For example, you could define a helper like this one:
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);
};
Then, in your template, you would loop through like this:
{@iter obj=Undergradaute.Offcampus.FeesItems}
{$value.label}, {$value.value}{~n}
{/iter}
Upvotes: 0