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.
You can create a function to reduce to an object, then store in a variable.
In your HTML, you can iterate with the keyvalue pipe.