gpt4 book ai didi

angular - 如何在 Angular 中显示分组数组?

转载 作者:行者123 更新时间:2023-12-03 23:43:07 24 4
gpt4 key购买 nike

我有一个像这样的对象数组

[
{"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1},
{"desc":"d", "menu": 3},{"desc":"e", "menu": 3},{"desc":"f", "menu": 2},
{"desc":"g", "menu": 1},{"desc":"g", "menu": 1},{"desc":"g", "menu": 4},
{"desc":"g", "menu": 4},{"desc":"g", "menu": 4}
]
从 API 获取。
现在我将显示带有 *ngFor 的对象通过将它们设置为按“菜单”分组并像这样向其添加标签
菜单 1
{菜单 1 的所有对象}
菜单 2
{菜单 2 的所有对象}
菜单 3
{菜单 3 的所有对象}
我会在 *ngFor 中做这样的事情
*ngFor="let object of objects; let menu = 0"
if menu !== object.menu
menu === object.menu
WRITE LABEL
但是我怎么能在一个真实的案例代码中实现它呢?

最佳答案

我认为我们应该在使用之前对其进行分组 *ngFor这是解决方案

 function groupBy(array, fn) {
return array.reduce(
(acc, current) => {
const groupName = typeof fn === 'string' ? current[fn] : fn(current);
(acc[groupName] = acc[groupName] || []).push(current);
return acc;
},
{}
);
}

function toArray(obj) {
return Object.keys(obj).map(k => obj[k]);
}

const data = [
{"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1},
{"desc":"d", "menu": 3},{"desc":"e", "menu": 3},{"desc":"f", "menu": 2},
{"desc":"g", "menu": 1},{"desc":"g", "menu": 1},{"desc":"g", "menu": 4},
{"desc":"g", "menu": 4},{"desc":"g", "menu": 4}
]

const groupMenu = groupBy(data, (item) => item.menu);
然后在模板中
<group *ngFor="let group of groupMenu">
<menu *ngFor="let menu of group">
<label>{{menu.desc}}</label>
</menu>
</group>

关于angular - 如何在 Angular 中显示分组数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64569084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com