angular 7 - list for unique items in json array

290 Views Asked by At

I have a json array like below ,

 items=[
    {name:"first",subname:"first 1"},
    {name:"first",subname:"first 2"},
    {name:"first",subname:"first 3"},
    {name:"second",subname:"second 1"},
    {name:"second",subname:"second 2"}
    ];

Which i want to display as list like,

first
   first 1
   first 2
   first 3
second
   second 1
   second 2

Though I achieved this by putting two functions in component.ts

getsubname(name){
  return this.items.filter(
      function(data){return data.name == name}
  );
}
getnames(){
  var disname =  this.items.map(item => item.name)
  .filter((value, index, self) => self.indexOf(value) === index)
  return disname
} 

and put them in HTML like below,

<div>
<mat-list>
    <ng-container *ngFor="let item of getnames()">
        <mat-list-item>{{item}}</mat-list-item>
        <mat-list style="margin-left:30px;">
            <div *ngFor="let subItem of getsubname(item)">
                <mat-list-item >{{ subItem.subname }}</mat-list-item>      
            </div>
        </mat-list>
    </ng-container>
</mat-list>
</div>

But this method looks very naive. I am sure there must me better way to do this. Please suggest.

1

There are 1 best solutions below

2
On

You can create a function to reduce to an object, then store in a variable.

 values = {};

 getValues (){
   return this.items.reduce((acc , prev) => {
    let ele = prev.name;
     if (!acc[ele]) {
       acc[ele] = [];
     }  
    acc[ele].push(prev.subname);
    return acc;
   }, {});
}


ngOnInit() {
    this.values = this.getValues();
  }

In your HTML, you can iterate with the keyvalue pipe.

<div>
  <ul *ngFor="let item of values | keyvalue">
    {{ item.key }}
    <li *ngFor='let val of item.value'>
      {{ val }}
    </li>
  </ul>
</div>