1

I know that the traditional syntax for looking up array values (by key) in Ember is to use .[] syntax, like:

{{myArray.[0]}}

However, I have an associative array, and despite having a separate model/controller property that lists the keys, I'm unable to perform a lookup - the value is always undefined.

As an example, here is a simple controller:

App.IndexRoute = Ember.Route.extend({
    model: function () {
        var ret = [];
        ret['notGreat'] = ['Plain Yogurt', 'Clams'];
        ret['great'] = ['Pizza', 'Chicken'];
        return Ember.RSVP.hash({
            keys: ['great', 'notGreat'],
            array: ret
        });

    }
});

And my template uses:

    {{#each key in model.keys}}
      <li>{{key}}</li>
      {{#each subItem in model.array.[key]}}
          <li>Subitem: {{subItem}}</li>

Though the model.array.[key] always seems to be undefined. Is there a trick to associative array lookups in Ember? I would also be happy writing a controller function like getFoodsWithKey(key), but haven't found any resources indicating that calling a controller function (as opposed to a computed property, which to support their caching paradigm, doesn't allow parameters) is possible.

JSFiddle (array notation): http://jsfiddle.net/6Evrq/786/

JSFiddle (object property notation): http://jsfiddle.net/6Evrq/787/

Craig Otis
  • 31,257
  • 32
  • 136
  • 234
  • Please note that JS doesn't have "associative arrays", though it does have objects which can have keys to accomplish the same thing. In short, `var ret = []; ret['foo'] = 'bar';` is improper and should not be used. Instead, use `var ret = {}; ret['foo'] = 'bar';`. See also: http://stackoverflow.com/q/874205/84473 – ken Oct 21 '16 at 20:51

1 Answers1

2

If you're using Ember 2.0+ you can use the each-in helper which was announced here.

The template would become:

<ul>
{{#each-in model.array as |key value|}}
  <li>{{key}}: {{value}}</li>
{{/each-in}}
</ul>

The get helper can also be used to get a specific value by its key:

{{get items 'Item 1'}}
{{get items somePathWithAKey}}

JSBin demo

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • That's great, thanks - this works for a situation in which you want to print _all_ the elements (with their keys), which is what I described. But as an addendum, do you know if there's a way to access a `value` given a _specific_ `key`? – Craig Otis Dec 14 '15 at 22:42
  • @CraigOtis yes, you can use the `get` helper. Updated my post and demo with examples. Unfortunately I can't find this in the official docs, just the announcement link. – Ahmad Mageed Dec 14 '15 at 23:03