Quoting through an array of arrays in Ember

I am a little newbie and am confused in Ember iterations.

I am trying to create a select inside an ember template, for example:

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

Here stateArrays looks like this:

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

But this gives rise to an error. When I try {{stateArray}} , I get a string like "1, Albama" ...

How to achieve the above in a single iteration?

+5
source share
2 answers

You can convert an array of arrays to 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 like:

 <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.

UPDATE

If you do not want to create another array ( mappedArray ), you can write an assistant:

 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}}>{{get-array-item stateArray 1}}</option> {{/each}} </select> 
+1
source

Not that I liked this technique, but you can access individual elements in an array like this

 {{#each stateArrays as |stateArray|}} <option value={{stateArray.[0]}}>{{stateArray.[1]}}</option> {{/each}} 

Twiddle

Remains the need to write additional code.

+2
source

Source: https://habr.com/ru/post/1259403/


All Articles