xckpd7 xckpd7 - 11 months ago 64
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):

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

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.


(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}}

For objects:

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

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