我有以下数组,如果grouptype
相同,我需要结果来合并结果。
const locationss = [
{
grouptype: "Name1",
id: "1",
servicetype: [
{ name: "Morning", price: "5" },
{ name: "Afternoon", price: "5" },
{ name: "Full Day", price: "5" },
],
},
{
grouptype: "Name1",
id: "2",
servicetype: [
{ name: "Morning1", price: "5" },
{ name: "Afternoon1", price: "5" },
{ name: "Full Day1", price: "5" },
],
},
{
grouptype: "Name2",
id: "3",
servicetype: [
{ name: "Morning", price: "5" },
{ name: "Afternoon", price: "5" },
],
},
];
我希望结果是,我试过了。减少,但这并不起作用。
{
grouptype: 'Name1',[
{ name: 'Morning', price: '5' },
{ name: 'Afternoon', price: '5' },
{ name: 'Full Day', price: '5' },
{ name: 'Morning1', price: '5' },
{ name: 'Afternoon1', price: '5' },
{ name: 'Full Day1', price: '5' },
]
},
{
grouptype: 'Name2',
id: '3',
servicetype: [
{ name: 'Morning', price: '5' },
{ name: 'Afternoon', price: '5' },
],
}
所以我可以把它放进一个表里。使用firebase支持
1条答案
按热度按时间qmb5sa221#
您可以使用
reduce()
按servicetype
分组,然后使用Object.entries()
和map()
将组Map到预期的输出结构。作为这一行的简短解释:
这里我们从一个空对象
{}
开始,然后检查数组中每个元素的组。当我们没有组作为对象中的键时(总是发生在第一个元素上),那么我们将创建一个新的组,这意味着我们为键grouptype
分配一个空数组作为值,然后推入所有的服务类型(push()
确实接受Iterable
)。如果我们已经有了组的键,那么我们也已经有了该组的数组,我们可以再次在服务类型中使用push()
。使用nullish assignment operator可以很容易地实现此逻辑。