Handlebars - How to navigate JSON data for template

て烟熏妆下的殇ゞ 提交于 2020-01-17 05:40:08

问题


I have JSON data that look like:

{ "review": { "count": "1", "summary": [ { "Q1": "9.50", "Q2": "9.50", "Q3": "9.00", "Q4": "8.75", "Q5": "7.63", "Q6": "8.88", "Q7": "9.38", "Q8": "9.75", "Q9": "9.38", "Q10": "9.00", "Q11": "9.75", "Q12": "9.75", "Q13": "9.75", "Q14": "8.13", "Q15": "9.00", "Q16": "8.88", "Q17": "8.00", "Q18": "9.38", "Q19": "9.88", "Q20": "10.00", "Q21": "10.00", "Q22": "7.00", "Q23": "9.75", "Q24": "9.25", "Q25": "8.63", "Q26": "9.00", "Q27": "6.50", "Q28": "9.50", "Q29": "9.63", "Q30": "9.75", "Q31": "9.38", "Q32": "8.63", "Q33": "9.50", "Q34": "7.38", "Q35": "6.88", "Q36": "7.38", "Q37": "9.88", "Q38": "9.50", "Q39": "7.75", "Q40": "8.25", "Q41": "9.75", "Q42": "9.75", "Q43": "9.63", "Q44": "9.38", "Q45": "9.88", "Q46": "9.38", "Q47": "10.00", "Q48": "9.88", "Q49": "10.00", "Q50": "9.88", "Q51": "9.75", "Q52": "9.38" } ] } }

I am trying to create a Handlebars template that allows me to iterate a certain div block. I am trying to list the @index values for the "summary" section, but can't seem to find the correct syntax to get at them.

I can get

{{#each reviews.summary}}

{{/each }} 

I have tried to use {{#key}} within that each statment, but I get 0 - which is the array key for the first item in "summary". How could I output the list of key values within that array? Essentially, Q1, Q2,...etc.


回答1:


edit:

this works for the first property:

{{#each review.summary}}
    {{Q1}}
{{/each }}

edit:

handlebars template:

{{#each qdata}}
    {{this}}
{{/each }}

js:

// new function:
function getQData(data) {
    var arQData = [];
    var obj = data.review.summary[0]; // here's the data we need.

    for (var prop in obj) {
        //alert("obj." + prop + " = " + obj[prop]);
        arQData.push(obj[prop]);
    }
    return arQData;
}

// create a new object for the filtered data. this seemed
// necessary (?) so i could put 'qdata' in the html template.
// call (new) function that does the filtering. 
// dataIn argument is the JSON data.
var d = { qdata: getQData(dataIn) };

// handlebars stuff.
var context = d;
var html = template(context);
$("#results").html(html); // wherever your results go.

object properties: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in



来源:https://stackoverflow.com/questions/33086322/handlebars-how-to-navigate-json-data-for-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!