Search code examples
javascriptjqueryjsonbackbone.jsunderscore.js

Underscore _each. function getting nested object in loop


Fiddle here:

http://jsfiddle.net/rBhfx/79/

In this for loop within an underscore template: <% for(var item in thing.items) { %>

I wanted to get item.name, but the <%= item.name %> is not outputting anything.

How do I get the properties from each things.items object? Thanks!

my JSON data looks like this:

var things = [{
    "name": "Chair",
    "title": "Chairs",
    "items": [{
           "name": "Recliner",
           "title": "Recliner Chair",
           "type": "Chair",
           "quantity": "1"
        }, 
        {
           "name": "Club/Armchair",
           "title": "Club/Armchair",
           "type": "Chair",
           "quantity": 1
        }]
}, 
{
   "name": "Table",
   "title": "Tables",
   "items": [{
           "name": "End Table",
           "title": "End Table",
           "type": "Table",
           "quantity": "1"
        }, 
        {
           "name": "Coffee Table",
           "title": "Coffee Table",
           "type": "Table",
           "quantity": 1
        }]
}];

And my template looks like this:

<script type="text/html" id='furniture-template'>
        <% _.each(things,function(thing,key,list){ 
            // create more variables
        %>
            <div class="accordion-heading">
                <a class="accordion-toggle" data-toggle="collapse" href="#things-<%= thing.name %>">
                    <%= thing.title %>
                </a>
            </div> <!-- header -->

            <div id="things-<%= thing.name %>" class="accordion-body collapse in">
                <div class="accordion-inner">
                    <% for(var item in thing.items) { %>
                    <div class="item">
                        <a class="item-add" data-type="Chairs" data-name="Recliner"><%= item.name %></a>
                    </div>
                    <% } %>
                </div> <!-- inner -->
            </div> <!-- accordion-body -->

        <% }); %>
</script>

Solution

  • <%= thing.items[item].name %> Worked!

    http://jsfiddle.net/rBhfx/86/