How to Iterate over a hash in mustache.js

Posted on

How to Iterate over a hash in mustache.js

Given this hash

a = {
  foo : { ... },
  bar : { ... },
  zap : { ... }

i want to iterate over it but since the keys are different I am not sure how to in Mustache.js

the output will look something like this foo : (contents here)

Solution :

If you know the key in the nested object that you’re trying to retrieve, you can use a function.



$(function() {
    var names = {
        "a": [
            {"foo": { "name": "foo name"}},
            {"bar": { "name": "bar name"}},
            {"zap": { "name": "zap name"}}
        "n": function() {
            var self = this;
            var n = "";
            Object.keys(self).forEach(function(k, v) {
                if (typeof self[k] == "object") {
                    if(!n) n = self[k]["name"];
            return n;

    var template = $('#template').html();
    var out = $('#output');
    var html = Mustache.to_html(template, names);


<script id="template" class="template" type="text/x-mustache">

<div id="output">

This of course assumes your data is an array of objects (the a in your post would be one key of a greater array, maybe?) If you don’t have an array, I don’t see why you wouldn’t be able to adjust this for an object and make a getter function for whatever properties of each key you’re looking for.

Leave a Reply

Your email address will not be published. Required fields are marked *