htmlbars icon indicating copy to clipboard operation
htmlbars copied to clipboard

Access array by index inside "each" block

Open dmoreno opened this issue 9 years ago • 10 comments

I have two arrays:

var array1 = [ "a", "b", "c"];
var array2 = [ "x", "y", "z"];

And I try to interate with an each block by this way:

{{#each array1 as |item index|}}
  1. {{index}} : {{item}}
  2. {{array2.[0]}}
  3. {{array2.[index]}}
{{/each}}

First and second lines works as expected. But third line is empty.

I tried several ways but no one works:

array2.index
array2.[index]
array2.[(index)]
array2.[@index]

What is the way to interate over a second array using index? Could it be a bug?

dmoreno avatar Jul 16 '15 15:07 dmoreno

ah looks like you are trying to zip two arrays together?

an interesting idea may be.

{{#each (zip array1 array2) as |tuple, index|}}
  {{tuple.0}} || {{tuple.1}}
{{/each}}

we could go all lisp (but it feels strange)

{{#each (zip array1 array2) as |tuple, index|}}
  {{car tuple}} || {{cdr tuple}}
{{/each}}

stefanpenner avatar Jul 16 '15 15:07 stefanpenner

{{array2.[index]}}

some people may view this as WAT, but I think it would be good.

stefanpenner avatar Jul 16 '15 15:07 stefanpenner

I think that syntax {{array2.[index]}} makes sense and it is consistent with the rest of the htmlbars syntax.

And your idea about zip helper is interesting too. But, at least for me, it could be the second option.

dmoreno avatar Jul 16 '15 16:07 dmoreno

cc @mmun

stefanpenner avatar Jul 16 '15 17:07 stefanpenner

So, you can do it with native arrays and the get() helper or create an index-of helper. But maybe this warrants a syntax? We should either close and open a different issue with that suggestion or change the title of this issue.

http://emberjs.jsbin.com/wocedobavu/1/edit?html,js,console,output

krisselden avatar Jul 16 '15 20:07 krisselden

array2.[index] already means something. It's would be breaking to change it. We could consider array2[index].

mmun avatar Jul 16 '15 21:07 mmun

Any updates on that?

egemon avatar Jun 16 '17 14:06 egemon

@egemon This should have been closed as working. What's the issue you're running into? You should be able to use (get array index) in Ember to fetch an array index.

mmun avatar Jun 16 '17 17:06 mmun

Possibly related https://github.com/emberjs/ember.js/pull/15366

mmun avatar Jun 16 '17 17:06 mmun

From what version this should work?

egemon avatar Jun 16 '17 17:06 egemon