Using array indices in Ember template


#1

Hi,

If I have an array in my controller/component like myarray:[“ben”,“beng”, “benglancy”]

In my template can I access the third element of this array directly?

And similarly if I have a recordarray can I access a particular one to access to fields in the model (element) in the template or do I have to create a computedproperty to filter/find it.


#2

You can do:

{{get someArray "3"}}

As of Ember 2.14.0 you will be able to use either a string or number for the second param, but in older Ember versions you can only use a string.


#3

Does not seem to work. I have a model.genericdata, a record array result from .query() in the router. I just wanted to access the first item. If the index leads to an object, how would you access a field of this “3”.


#4

If you just want the first object you can do:

{{someArray.firstObject.propertyName}}

#5

Nope, doesn’t work.

I am passing my model to the component, model. genericdata is the result of a query() in the router.

{{model.genericdata.value_string}}

Its fine if I use {{initial_instruction}} with a computed property:

initial_instruction : Ember.computed('model.genericdata', function() {
	return this.getGenericData("categories3_header").get('value_string');
}),
where
   getGenericData(key) {
	return this.get('model.genericdata').find(function (item) { 
			return item.get('key_string') === key;  
		},  this.get('model.genericdata'));
},

#6

try this add-on:

{{object-at 2 yourArray}}


#7

Thanks I’ll check that, though wish there was something in the Ember.js out of the box.


#8

You can try this hack

{{myarray.[2]}}


#9

Or just write a super simple helper yourself:

// app/helpers/get-array-element.js
import Ember from 'ember';

const {
  Helper,
  typeOf: getTypeOf
} = Ember;

export function getArrayElement([arr, i]) {
  if (getTypeOf(arr) !== 'array' || getTypeOf(i) === 'undefined') {
    return null;
  }
  return arr[i];
}

export default Helper.helper(getArrayElement);

And then:

{{get-array-element myArray 3}}