xckpd7 xckpd7 - 4 months ago 19
jQuery Question

Iterate over an object for Handlebars?

So this is the general gist of my data (copied the look from chrome webkit inspector).

> Object
> Fruit: Array[2]
> 0: Object
name: "banana"
color: "yellow"
animalthateats: "monkey"
id: 39480
> 1: Object
length: 2
> Vegetables: Array[179]
> Dairy: Array[2]
> Meat: Array[3]
> __proto__: Object


And this is what I want to do (in general):

<select>
<option value="">All Shows (default)</option>
<optgroup label="Fruit">
<option value="39480">Banana</option>
<option value="43432">Strawberry</option>
</optgroup>
<optgroup label="Vegetables">
<option value="3432">Broccoli</option>
</optgroup>
</select>


I'm sorta new to the whole templating thing, and it definitely seems non-straightforward to accomplish... if I can use jQuery anyway that will work too, but preferably just with this setup.

Answer

(From http://stackoverflow.com/a/17516837/362042)

Built-in support since Handlebars 1.0rc1

Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.

How to use it

For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.