当它与上一个不同时,我如何遍历对象数组并更改组标签?
How can i iterate over array of objects and change group label when its different than last one?
我有一个对象数组,如下所示:
[
{group_label: Colors, label: Red, value: '1'},
{group_label: Colors, label: Green, value: '2'},
{group_label: Sizes, label: S, value: '3'},
{group_label: Sizes, label: M, value: '4'},
{group_label: Sizes, label: L, value: '5'}
]
我想用 *ngFor 迭代它并得到这个结果:
Colors:
Red: 1
Green: 2
Sizes:
S: 3
M: 4
L: 5
我的问题是,如何在每个 "section" 开始时只显示一次 group_label。我无法将这些对象重新格式化为更适合此任务的内容,因为它们是 FormArrays 中的 Angulars FormGroup。
我认为唯一可能的方法是使用两个 ngFor 并制作自定义管道或具有分组功能的函数。之后你可以用第二个 ngFor 写出你的键值对。
一种最不优雅的方法是通过索引引用前一个元素,并检查 group_label 是否不同并创建它的新部分。在这种情况下,您的数组必须已经排序!
您可以创建一个管道来对这些进行分组:
@Pipe({name: 'group'})
export class GroupPipe implements PipeTransform {
transform(values: Array<any>): Array<any> {
// {group_label: Colors, label: Red, value: '1'}
const groups = values.reduce((all, row) => {
all[row.group_label] = all[row.group_label] || [];
all[row.group_label].push(row);
}, {});
return Object.keys(groups).map(group => ({ group_label: group, labels: groups[group]}));
}
}
现在使用嵌套的 ngFor:
<div *ngFor="let group of (unsortedGroups | group)">
{{ group.group_label }}
<div *ngFor="let label of group.labels">
{{ label.label }}: {{ label.value }}
</div>
</div>
我有一个对象数组,如下所示:
[
{group_label: Colors, label: Red, value: '1'},
{group_label: Colors, label: Green, value: '2'},
{group_label: Sizes, label: S, value: '3'},
{group_label: Sizes, label: M, value: '4'},
{group_label: Sizes, label: L, value: '5'}
]
我想用 *ngFor 迭代它并得到这个结果:
Colors:
Red: 1
Green: 2
Sizes:
S: 3
M: 4
L: 5
我的问题是,如何在每个 "section" 开始时只显示一次 group_label。我无法将这些对象重新格式化为更适合此任务的内容,因为它们是 FormArrays 中的 Angulars FormGroup。
我认为唯一可能的方法是使用两个 ngFor 并制作自定义管道或具有分组功能的函数。之后你可以用第二个 ngFor 写出你的键值对。
一种最不优雅的方法是通过索引引用前一个元素,并检查 group_label 是否不同并创建它的新部分。在这种情况下,您的数组必须已经排序!
您可以创建一个管道来对这些进行分组:
@Pipe({name: 'group'})
export class GroupPipe implements PipeTransform {
transform(values: Array<any>): Array<any> {
// {group_label: Colors, label: Red, value: '1'}
const groups = values.reduce((all, row) => {
all[row.group_label] = all[row.group_label] || [];
all[row.group_label].push(row);
}, {});
return Object.keys(groups).map(group => ({ group_label: group, labels: groups[group]}));
}
}
现在使用嵌套的 ngFor:
<div *ngFor="let group of (unsortedGroups | group)">
{{ group.group_label }}
<div *ngFor="let label of group.labels">
{{ label.label }}: {{ label.value }}
</div>
</div>