我有一个对象数组,它描述了一组图表类型。每个格式都是
{
name: 'Donut Chart',
category: ['comparisons'],
subcategory: ['proportions']
},
您会看到每个图表都有一个可以匹配的类别和子类别的数组。
我有2套复选框,“类别”和“子类别”。单击这些复选框之一,将所选类别添加到selectedCategories
数组中,并显示带有其自己的复选框的子类别列表。
如上所述,当选择了子类别时,这会将所选子类别添加到数组selectedSubcategories
中。
这时,我想显示与所选类别(在数组selectedCategories
中)和子类别(在数组selectedSubcategories
中)相匹配的图表类型列表。
我已经创建了此(工作)逻辑来显示复选框并添加/删除2个数组中的项目,但是我不清楚如何为chartsToDisplay
创建过滤器,该过滤器将在页面。
categories = [
{ name: 'Comparisons', filter: 'comparisons', selected: false },
{ name: 'Composition', filter: 'relationships', selected: false },
{ name: 'Distribution', filter: 'distribution', selected: false },
{ name: 'Individual Metric', filter: 'individual-metric', selected: false },
{ name: 'Relationships', filter: 'relationships', selected: false }
];
subcategories = [
{ name: 'Data over Time', filter: 'data-over-time', selected: false },
{ name: 'Patterns', filter: 'patterns', selected: false },
{ name: 'Location', filter: 'location', selected: false },
{ name: 'Proportions', filter: 'proportions', selected: false }
];
selectedCategories = [];
selectedSubcategories = [];
chartsToDisplay = [];
categorySelect(category) {
if (category.selected) {
this.selectedCategories.push(category.filter);
} else {
// remove un-checked item from the array
let toDel = this.selectedCategories.indexOf(category.filter);
this.selectedCategories.splice(toDel, 1);
}
if (!this.selectedCategories.length) {
this.subcategories.forEach(function(value, index) {
value.selected = false;
});
}
}
subcategorySelect(subcategory) {
if (subcategory.selected) {
this.selectedSubcategories.push(subcategory.filter);
} else {
// remove un-checked item from the array
let toDel = this.selectedSubcategories.indexOf(subcategory.filter);
this.selectedSubcategories.splice(toDel, 1);
}
}
我尝试只使用子类别,但是我什么也没得到:
filterCharts(subcats) {
this.displayedCharts = this.chartTypes.filter(c => c.subcategory === subcats);
}
在这种情况下可能并不重要,但这是我正在测试的HTML:
<ul>
<li *ngFor="let cat of categories">
<input type="checkbox"
[(ngModel)]="cat.selected"
(ngModelChange)="categorySelect(cat)"> {{cat.filter}}
</li>
</ul>
<ul *ngIf="selectedCategories.length">
<li *ngFor="let subcat of subcategories">
<input type="checkbox"
[(ngModel)]="subcat.selected"
(ngModelChange)="subcategorySelect(subcat)"> {{subcat.filter}}
</li>
</ul>
<h2>Charts</h2>
<ul>
<li *ngFor="let chart of displayedCharts">
{{chart.name}}
</li>
</ul>
答案 0 :(得分:0)
根据我对问题的理解和一些假设,我认为代码将需要以下内容。
如果图表列表位于名为charts
的变量中,则
charts.filter(chart =>
selectedCategories.every(c => chart.category.includes(c))
&& selectedSubcategories.every(sc => chart.subcategory.includes(sc))
)