使用 each 和 handlebars 助手对对象键进行排序

Sort object keys with each and handlebars helper

我想对每个对象键进行排序: 测试 1、测试 4、测试 3 => 测试 1、测试 3、测试 4 ...

我的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)。 希望对你有帮助。