admin管理员组

文章数量:1327750

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)

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)

Share Improve this question edited Apr 2, 2012 at 19:07 ZeissS 12.1k4 gold badges37 silver badges50 bronze badges asked Apr 2, 2012 at 18:37 samcconesamccone 10.9k7 gold badges44 silver badges50 bronze badges 1
  • Can you detail this a bit? Do you want to iterate the elements of foo, bar and zap or the keys itself? – ZeissS Commented Apr 2, 2012 at 18:44
Add a ment  | 

1 Answer 1

Reset to default 4

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

see: http://jsfiddle/jimschubert/zPWDJ/

js:

$(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);
    console.log(html);
    out.html(html);
});​

html:

<script id="template" class="template" type="text/x-mustache">
{{#a}}
<p>{{n}}</p>
{{/a}}
</script>

<h1>Output</h1>
<div id="output">
</div>
​

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.

本文标签: javascriptHow to Iterate over a hash in mustachejsStack Overflow