根据状态筛选数组内部的数组



我有一个包含多个数组的数组。样本数据如下:

[
[
{
"id":1,
"status":1
},
{
"id":2,
"status":2
},
{
"id":3,
"status":3
},
{
"id":4,
"status":4
}
],
[
{
"id":5,
"status":1
},
{
"id":6,
"status":2
},
{
"id":7,
"status":3
},
{
"id":8,
"status":4
}
],
[
{
"id":8,
"status":1
},
{
"id":9,
"status":1
}
]
]

我正在使用PrimeNg复选框。我的代码如下:

<h5>Multiple</h5>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="New York"
[(ngModel)]="selectedCities"
inputId="ny"
></p-checkbox>
<label for="ny">New York</label>
</div>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="San Francisco"
[(ngModel)]="selectedCities"
inputId="sf"
></p-checkbox>
<label for="sf">San Francisco</label>
</div>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="Los Angeles"
[(ngModel)]="selectedCities"
inputId="la"
></p-checkbox>
<label for="la">Los Angeles</label>
</div>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="Chicago"
[(ngModel)]="selectedCities"
inputId="ch"
></p-checkbox>
<label for="ch">Chicago</label>
</div>

Stacklitz如下:

https://stackblitz.com/edit/primeng-checkbox-demo-d9kasz?file=src%2Fapp%2Fapp.component.html

我想要对数组进行过滤,使得如果";纽约";则每个内部数组应该只有状态为1的元素;旧金山";则每个内部数组应该只有状态为2的元素。如果";洛杉矶";则每个内部阵列应仅具有状态为3的元素。如果";芝加哥";则每个内部阵列应仅具有状态为4的元素。例如,如果";纽约";则最终输出应如下所示:

output : [
[
{
"id":1,
"status":1
}
],
[
{
"id":5,
"status":1
}
],
[
{
"id":8,
"status":1
},
{
"id":9,
"status":1
}
]
]

等等用于其他元件。我该怎么做?

您可以在组件中对用于构建表单的数据进行建模,如下所示:

type City = {
status: Number;
inputId: string;
name: string;
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
//...
cities: City[] = [
{ status: 1, name: 'New York', inputId: 'ny' },
{ status: 2, name: 'San Francisco', inputId: 'sf' },
{ status: 3, name: 'Los Angeles', inputId: 'la' },
{ status: 4, name: 'Chicago', inputId: 'ch' },
];
//...

这样,您就可以根据组件数据动态构建表单。

<h5>Multiple</h5>
<div class="p-field-checkbox" *ngFor="let city of cities">
<p-checkbox
name="group1"
[value]="city"
[(ngModel)]="selectedCities"
[inputId]="city.inputId"
></p-checkbox>
<label [for]="city.inputId"> {{ city.name }}</label>
</div>

选中复选框后,所选城市的城市对象将存储在selectedCities数组中,然后您可以使用selectedCities的状态来过滤组件中的给定数组。

为了本练习的目的,让我们将您的数组命名为collectionGroup

const EMPTY = [];
//...
const statuses: Number[] = this.selectedCities.map(city => city.status);
const filteredCollectionGroup =
statuses.length > 0
? this.collectionGroup.map((collection) => {
return collection.filter(
(item) => statuses.indexOf(item.status) > -1
);
})
: EMPTY;

最新更新