按照分组名称和子项对对象数组进行分组。
创始人
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",
//          

相关内容

热门资讯

透视教学!hhpoker视频巡... 透视教学!hhpoker视频巡查真的假的(透视)本来真的有挂(详细辅助新2025版);1、透视辅助简...
透视线上!wepokerh5破... 透视线上!wepokerh5破解(透视)本来有挂(详细辅助分享教程)运辅助工具,进入游戏界面。进入辅...
透视科技!hhpoker德州有... 透视科技!hhpoker德州有挂吗(透视)真是真的是有挂(详细辅助微扑克教程);1、玩家可以在软件透...
透视脚本!如何下载wepoke... 透视脚本!如何下载wepoker安装包(透视)本来是有挂(详细辅助黑科技教程);1、许多玩家不知道辅...
透视挂!德普之星透视软件免费入... 透视挂!德普之星透视软件免费入口官网(透视)都是是真的有挂(详细辅助技巧教程);1、完成透视辅助安装...
透视有挂!wpk模拟器多开(透... 透视有挂!wpk模拟器多开(透视)竟然是有挂(详细辅助透牌教程);1、完成透视辅助安装,帮助玩家取得...
透视好牌!wepoker好友房... 透视好牌!wepoker好友房开挂(透视)总是真的是有挂(详细辅助2025新版技巧)1)辅助挂:进一...
透视游戏!聚星ai辅助工具收费... 透视游戏!聚星ai辅助工具收费多少(透视)果然有挂(详细辅助黑科技教程)1、超多福利:超高返利,海量...
透视美元局!hhpoker怎么... 透视美元局!hhpoker怎么开透视(透视)竟然是真的有挂(详细辅助攻略方法)1、hhpoker怎么...
透视数据!hhpoker透视脚... 透视数据!hhpoker透视脚本视频(透视)总是有挂(详细辅助实用技巧)一、hhpoker透视脚本视...