Search code examples
javascriptember.jsember-clihtmlbars

Accessing indexed item from array in HTMLBars


I have a custom API that is not formatted for easy use with Ember Data. I'm having trouble getting the value of nested array properties from my api.

api response:

{
  "data": [
    {
      "id": 6,
      "name": "Company Name",
      "links": [
        {
          "rel": "self",
          "uri": "/address-book/company-name"
        }
      ],
      "details": {
        "data": {
          "website_url": "http://website.com/",
          "development_website_url": "http://dev_website.com",
          "primary_phone": 9543333333,
          "primary_email": "[email protected]"
        }
      }
    },
    {
      "id": 3,
      "name": "Company Name",
      "links": [
        {
          "rel": "self",
          "uri": "/address-book/company-name"
        }
      ],
      "details": {
        "data": {
          "website_url": "http://website.com/",
          "development_website_url": "http://dev_website.com",
          "primary_phone": 9543333333,
          "primary_email": "[email protected]"
        }
      }
    }
  ]
}

I'm trying to get the links displayed here is my handlebars:

{{#each m in model}}
    <tr>
        <td>
            <a href="{{m.links.uri}}">{{m.name}}</a>
        </td>
    </tr>
{{/each}}

Now the link uri is just blank. If I change it to just {{m.links}} that return {object object}. I've also tried {{m.links[0].uri}} just to see if that would work but no good.

Here is my router and the adapter used for it.

export default Ember.Route.extend({
    model: function(){
        var adapter = AddressBookAdapter.create();
        var companies =  adapter.findAll();
        return companies;

    }
});

adapter:

export default Ember.Object.extend({
    findAll: function(){
        return ajax('http://localhost:8000/api/v1/address-book/companies?includes=details')
            .then(function(response){
                return response.data;
            });
    }
});

How can I get the value of these properties? I feel like it's really easy and I'm just not getting it.


Solution

  • To access element at specific index of array in template, you should use syntax {{array.[index]}}

    According to your api response, this should probably work:

    {{#each m in model}}
        <tr>
            <td>
                <a href="{{m.links.[0].uri}}">{{m.name}}</a>
            </td>
        </tr>
    {{/each}}