Abhi Abhi - 11 months ago 61
Javascript Question

Looping through Array of Arrays in Ember

I'm bit new and confused about Ember iterations.

I'm trying to construct a select inside ember template, like:

<select id="state_list">
{{#each stateArrays as |stateArray|}}
<option value={{stateArray[0]}}>{{stateArray[1]}}</option>

looks like:

[[1, "Alabama"], [2, "Alaska"], [3, "Arizona"]]

But, this throws error. When I try
, I get string like
"1, Albama"

How to achieve the above in single iteration?

Answer Source

You can convert the array of arrays into an array of objects

mappedArray = [[1, "Alabama"], [2, "Alaska"], [3, "Arizona"]].map(function(array){ return { num: array[0] , str: array[1] }; })

Then you can use it as:

<select id="state_list"> {{#each mappedArray as |obj|}} <option value={{obj.num}}>{{obj.str}}</option> {{/each}} </select>

Basically we cannot use syntax like stateArray[0] in the template.


If you don't want to create another array (mappedArray), you can write a helper:

App.GetArrayItemHelper = Ember.Helper.helper(function (values) { var array = values[0], index = values[1]; return array[index] })

Then in your template:

<select id="state_list"> {{#each stateArrays as |stateArray|}} <option value={{get-array-item stateArray 0}}>{{et-array-item stateArray 1}}</option> {{/each}} </select>