按照分组名称和子项对对象数组进行分组。
创始人
2024-08-24 00:00:42
0

假设有一个对象数组,每个对象包含一个分组名称和各个子项,要将这些对象按照分组名称和子项进行分组,可以使用reduce和对象的key来实现:

const data = [
  { group: 'A', children: ['a1', 'a2', 'a3'] },
  { group: 'B', children: ['b1', 'b2', 'b3'] },
  { group: 'A', children: ['a4', 'a5'] },
  { group: 'C', children: ['c1', 'c2', 'c3'] },
  { group: 'B', children: ['b4', 'b5', 'b6'] },
];

const result = data.reduce((acc, item) => {
  // 如果当前分组名称不存在,则添加该分组
  if (!acc[item.group]) {
    acc[item.group] = {};
  }
  
  // 将当前子项加入对应的分组中
  item.children.forEach(child => {
    if (!acc[item.group][child]) {
      acc[item.group][child] = [];
    }
    acc[item.group][child].push(item);
  });
  
  return acc;
}, {});

console.log(result);

// 输出结果:
// {
//   "A": {
//     "a1": [
//       {
//         "group": "A",
//         "children": [
//           "a1",
//           "a2",
//           "a3"
//         ]
//       }
//     ],
//     "a2": [
//       {
//         "group": "A",
//         "children": [
//           "a1",
//           "a2",
//           "a3"
//         ]
//       }
//     ],
//     "a3": [
//       {
//         "group": "A",
//         "children": [
//           "a1",
//           "a2",
//           "a3"
//         ]
//       }
//     ],
//     "a4": [
//       {
//         "group": "A",
//         "children": [
//           "a4",
//           "a5"
//         ]
//       }
//     ],
//     "a5": [
//       {
//         "group": "A",
//         "children": [
//           "a4",
//           "a5"
//         ]
//       }
//     ]
//   },
//   "B": {
//     "b1": [
//       {
//         "group": "B",
//         "children": [
//           "b1",
//          

相关内容

热门资讯

黑科技了解(wepoke智能a... 黑科技了解(wepoke智能ai)wepoke有挂吗网上(wePOke)最初有挂(有挂分享)-哔哩哔...
黑科技讲解(wepoke辅助插... 黑科技讲解(wepoke辅助插件)wepooke app系统规律(wePoKe)往昔真的是有挂(有挂...
黑科技神器(wepoke智能a... 黑科技神器(wepoke智能ai)wepoke智能ai什么意思(wePoke)原先真的有挂(有挂详细...
黑科技私人局(wepoke辅助... 黑科技私人局(wepoke辅助插件)wepoke有挂吗蓝鸟(wEpOke)从来存在有挂(有挂详细)-...
黑科技肯定(wepoke真的有... 黑科技肯定(wepoke真的有挂)wepoke开发者(wePoKe)竟然真的是有挂(有挂工具)-哔哩...
黑科技代打(wepokeai代... 黑科技代打(wepokeai代打)wepoke辅助插件好用吗(wepoker)一贯真的是有挂(有挂方...
黑科技肯定(wepokeai代... 黑科技肯定(wepokeai代打)wopoker真的有挂吗(WepOke)固有是真的有挂(有挂助手)...
黑科技神器(wepoke智能a... 黑科技神器(wepoke智能ai)wepower德州扑克(Wepoke)先前是有挂(有挂攻略)-哔哩...
黑科技规律(wepokeai代... 相信很多朋友都在电脑上玩过吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编给大家带来了手机版,这...
黑科技能赢(wepoke辅助插... 黑科技能赢(wepoke辅助插件)wepoke打伙牌(Wepoke)总是有挂(确实有挂)-哔哩哔哩科...