I have an object of arrays that looks like this
const books = {
__typename: '',
items: [
{
id:''
store: 1
type: 'ROMAN'
name: 'blalala'
}
{
id:''
store: 1
type: 'BIOGRAPHY'
name: 'blalala'
}
{
store: 1
id:''
type: 'ROMAN'
name: 'blalala'
}
{
id:''
store: 2
type: 'ROMAN'
name: 'blalala'
}
]
What I need is to have a mat select containing only the books of type Roman in each store like this
<mat-select formControlName="booksForm">
<mat-optgroup *ngFor="let store of stores" [label]="books.store"
[disabled]="store.disabled">
<mat-option *ngFor="let romanBook of books" [value]="books.items.name">
{{ romanBook.name }}
</mat-option>
</mat-optgroup>
</mat-select>
I don't know how to loop over the data to get only the stores that contain books of type ROMAN and then loop over the roman books in that specific store to show them as mat-option, any ideas or help ?
Just iterate over your items and add them to a new array with objects corresponding to your stores
const books = {
__typename: '',
items: [
{
id:'',
store: 1,
type: 'ROMAN',
name: 'blalala'
},
{
id:'',
store: 1,
type: 'BIOGRAPHY',
name: 'blalala'
},
{
store: 1,
id:'',
type: 'ROMAN',
name: 'blalala'
},
{
id:'',
store: 2,
type: 'ROMAN',
name: 'blalala'
}
]
}
let stores = []
for (let i = 0; i < books.items.length; i++) {
if (books.items[i].type === 'ROMAN') {
const index = stores.findIndex(elem => elem.id === books.items[i].store)
if (index != -1) {
stores[index].books.push(books.items[i])
}else{
stores.push({id:books.items[i].store,books:[books.items[i]]})
}
}
}
console.log(stores)
You can remove if (books.items[i].type === 'ROMAN') if you want to have all your books whatever their type, and then in html template check weither it's ROMAN or anything else with a *ngIf