How to Iterate over a hash in mustache.js

后端 未结 1 625
攒了一身酷
攒了一身酷 2021-01-19 03:01

Given this hash

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

i want to iterate over it but since the keys are different I am n

相关标签:
1条回答
  • 2021-01-19 03:09

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

    see: http://jsfiddle.net/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.

    0 讨论(0)
提交回复
热议问题