gpt4 book ai didi

javascript - 如何制作 Primeng 通用组数组

转载 作者:行者123 更新时间:2023-12-02 22:04:46 24 4
gpt4 key购买 nike

我的目标:

users = [
{id: 1, name: "name1", company: "com1"},
{id: 2, name: "name2", company: "com2"},
{id: 3, name: "name3", company: "com1"},
{id: 4, name: "name4", company: "com2"},
{id: 5, name: "name5", company: "com3"},
]

对于 primeng 下拉列表,我需要将其转换为首选对象,我该如何使用 Angular 2 来做到这一点,如下所示。

我想要制作的对象:

[
{
label: 'com1',
items: [
{id: 1, name: "name1", company: "com1"},
{id: 3, name: "name3", company: "com1"}
]
},
{
label: 'com2',
items: [
{id: 2, name: "name2", company: "com2"},
{id: 4, name: "name4", company: "com2"}
]
},
{
label: 'com3',
items: [
{id: 5, name: "name5", company: "com3"},
]
}
]

最佳答案

我认为你可以使用Array.prototype.reduce()Array.prototype.find()组合。

reduce() 的文档状态:

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

对于find():

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

请在下面找到一个工作示例:

const users = [
{id: 1, name: "name1", company: "com1"},
{id: 2, name: "name2", company: "com2"},
{id: 3, name: "name3", company: "com1"},
{id: 4, name: "name4", company: "com2"},
{id: 5, name: "name5", company: "com3"},
];

const result = users.reduce((a, {id, name, company}) => {
const found = a.find(e => e.label === company);

if (found) {
found.items.push({
id, name, company
});
} else {
a.push({
label: company,
items: [{id, name, company}],
});
}
return a;
}, []);

console.log(result);

+1建议:

如何以及在何处使用解构语句完全取决于您,但请考虑以下事项。我也曾想过在这里提供解决方案,即何时为 reduce() 解构当前项。如果我将 (a,c) => {} 用于 reduce() 而不是 (a, {id, name, company}) => { } 然后在数组的推送线中我可以使用 {...c} 代替。

希望对您有所帮助!

关于javascript - 如何制作 Primeng 通用组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59753043/

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