简体   繁体   中英

Sort object keys with each and handlebars helper

I would like to sort objects keys with each: test1, test4, test3 => test1, test3, test4 ...

My json:

"tests": {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
}

My handlebars code:

{{#each tests}}
    <h1>{{@key}}</h1>
    <ul>{{#eachSorted this}}<li>{{this}}</li>{{/eachSorted}}</ul>
{{/each}}

I tried but does not work:

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
})

you are rendering the whole object instead of the value. Try this:

{{#each tests}}
    <h1>{{@key}}</h1>
    <ul>{{#eachSorted this}}<li>{{this.value}}</li>{{/eachSorted}}</ul>
{{/each}}

Replace the eachSorted function with this:

 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)); 

Also, in your JSON tests is an object. Are you sure you can apply each to an object? Maybe you should use an array. You can change the JSON or you can make a registerHelper that creates an array from the values. Use: Object.values(tests) . Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM