next.js React Array -合并数据

nhaq1z21  于 2023-04-30  发布在  React
关注(0)|答案(1)|浏览(110)

我有以下数组,如果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支持

qmb5sa22

qmb5sa221#

您可以使用reduce()servicetype分组,然后使用Object.entries()map()将组Map到预期的输出结构。

const locations = [
  {
    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" },
    ],
  },
];

const groups = locations.reduce((all, cur) => ((all[cur.grouptype] ??= []).push(...cur.servicetype), all), {});
const output = Object.entries(groups).map(([k, v]) => ({ grouptype: k, servicetype: v }));
console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }

作为这一行的简短解释:

const groups = locations.reduce((all, cur) => ((all[cur.grouptype] ??= []).push(...cur.servicetype), all), {});

这里我们从一个空对象{}开始,然后检查数组中每个元素的组。当我们没有组作为对象中的键时(总是发生在第一个元素上),那么我们将创建一个新的组,这意味着我们为键grouptype分配一个空数组作为值,然后推入所有的服务类型(push()确实接受Iterable)。如果我们已经有了组的键,那么我们也已经有了该组的数组,我们可以再次在服务类型中使用push()
使用nullish assignment operator可以很容易地实现此逻辑。

相关问题