[英]Sort object keys with each and handlebars helper
我想對每個對象鍵進行排序:test1,test4,test3 => test1,test3,test4 ...
我的json:
"tests": {
"chapter1": {
"test1": 5,
"test4": 8,
"test3": 3
},
"chapter2": {
"test1": 1,
"test5": 14,
"test3": 12
}
}
我的車把代碼:
{{#each tests}}
<h1>{{@key}}</h1>
<ul>{{#eachSorted this}}<li>{{this}}</li>{{/eachSorted}}</ul>
{{/each}}
我試過但不起作用:
Handlebars.registerHelper('eachSorted', function(context, options) {
var ret = ""
Object.keys(context).sort().forEach(function(key) {
ret = ret + options.fn({key: key, value: context[key]})
})
return ret
})
您正在渲染整個對象而不是值。 嘗試這個:
{{#each tests}}
<h1>{{@key}}</h1>
<ul>{{#eachSorted this}}<li>{{this.value}}</li>{{/eachSorted}}</ul>
{{/each}}
用這個替換eachSorted
函數:
var tests = { "chapter1": { "test1": 5, "test4": 8, "test3": 3 }, "chapter2": { "test1": 1, "test5": 14, "test3": 12 } }; function eachSorted(context) { var ret = {}; Object.keys(context) .sort() .forEach(function(key) { ret[key] = context[key]; }); return ret; } console.log(eachSorted(tests.chapter1));
此外,在您的JSON tests
是一個對象。 您確定可以將each
應用於對象嗎? 也許你應該使用一個數組。 您可以更改JSON,也可以創建一個registerHelper,從值中創建一個數組。 使用: Object.values(tests)
。 希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.