Sebastian
Sebastian

Reputation: 49

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

Upvotes: 1

Views: 818

Answers (2)

Nico Diz
Nico Diz

Reputation: 1504

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.

Upvotes: 0

jensteichert
jensteichert

Reputation: 126

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

Upvotes: 2

Related Questions