Sandra Willford
Sandra Willford

Reputation: 3789

ngFor group by key and display key for each group

I need to sort out the best way to get my object grouped and then loop those groups in my template.

The data is not sent to me grouped so in my component, I add a key to each array in the object:

ngOnInit(): void {
    this.getEmailsService.emailsAPI().subscribe(
        data => {
            let firstChar: string
            this.results = data
            this.emails = this.results
            this.emails.forEach(element => {
                firstChar = element.sender_email.charAt(0);
                element.key = firstChar
                console.log(element)
            });
        }
    );
}

the resulting dictionary looks like this:

created: "2017-10-07T01:42:25.110747Z"
email_domain: "domain.com"
has_user_viewed: false
key: "j"
pk: "wGR"
sender_email:"[email protected]"
sender_name: null

then in my template I have:

<div class="col-sm-6 mb-3" *ngFor="let email of emails | filter : searchText">

what would be the best way to handle grouping this by the key value and then also displaying the "master" 'key' for each group? so that you had something like:

key 
->result
->result
->result 
key 
->result
->result
->result 

Upvotes: 0

Views: 5750

Answers (1)

Nicholas Pesa
Nicholas Pesa

Reputation: 2196

You should keep your Array of objects standard as all the same model in an array without keys. Then if you want to group your array by a specific field this is a handy array transformation that can be passed a field and group the entire array by whatever selector you choose:

transformArray(array: Array<any>, field) {
    if (array) {
      const groupedObj = array.reduce((prev, cur) => {
        if (!prev[cur[field]]) {
          prev[cur[field]] = [cur];
        } else {
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
    return [];
  }

This will group your array into objects with a 'key' of whatever you passed into the method and then a nested array called 'value' which has all the objects related to your grouping field.

Upvotes: 3

Related Questions