arraysember.jspropertiesember-datacomputed-values

How can I analyze Ember Data array elements (computed property?)?


I want to create unique abbreviations for each element of an array of Ember Data records. For example, suppose we have the following records in the Persons table:

name: Mike Jones
department: IT

name: Mike Smith
department: IT

name: John Doe
department: Accounting

name: Jane Doe
department: Accounting

What I would like is output like this:

IT
MJ: Mike Jones
MS: Mike Smith

Accounting
JoD: John Doe
JaD: Jane Doe    

As you can see, a unique abbreviation for each person can only be assigned by analyzing all items in the array.

This is a little like computing the number of remaining Todos in the Ember documentation: http://guides.emberjs.com/v2.0.0/object-model/computed-properties-and-aggregate-data/

But, that guide describes using a Controller, which I understand is outmoded, and it does not address working with Ember Data.

I assume my template would look like this, but what would I add to my route?

{{#each model as |department|}}
{{department.name}}
{{#each department.persons as |person|}}
{{person.computedAbbreviation}}: {{person.name}}
{{/each}}
{{/each}}

Solution

  • You will want to use a helper since this is a presentation issue:

    import Ember from 'ember';
    
    const { Helper: { helper } } = Ember;
    
    export function nameInitials([name]) {
      return name.match(/\b(\w)/g).join('').toUpperCase();
    }
    
    export default helper(nameInitials);
    

    And in your template you will use it:

    {{name-initials person.name}}

    For the case where you want the first 2 letters of the person's first name we would have to change the logic and resort to charAt the logic becomes:

    export function nameInitials([name]) {
      let [firstName, lastName] = name.split(' ');
      return `${firstName[0].toUpperCase()}${firstName[1]}${lastName[0].toUpperCase()}`;
    }