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

相关内容

热门资讯

解迷透视!红龙poker辅助工... 解迷透视!红龙poker辅助工具!切实是有辅助教程(有挂教程)-哔哩哔哩1、红龙poker辅助工具辅...
详情透视!pokemmo辅助官... 详情透视!pokemmo辅助官网!其实有辅助软件(发现有挂)-哔哩哔哩1、玩家可以在pokemmo辅...
必备透视!wepoker透视有... 必备透视!wepoker透视有吗!竟然有辅助教程(真是有挂)-哔哩哔哩1、点击下载安装,wepoke...
解谜透视!红龙poker辅助工... 解谜透视!红龙poker辅助工具!其实真的是有辅助插件(有挂秘笈)-哔哩哔哩1、下载好红龙poker...
必备透视!pokemmo辅助脚... 必备透视!pokemmo辅助脚本!都是是真的有辅助神器(存在有挂)-哔哩哔哩所有人都在同一条线上,像...
教你透视!pokemmo辅助器... 教你透视!pokemmo辅助器!真是是真的有辅助app(有挂技术)-哔哩哔哩1、完成pokemmo辅...
专业透视!德州透视是真的假的!... 专业透视!德州透视是真的假的!一直存在有辅助工具(有挂秘笈)-哔哩哔哩1、德州透视是真的假的破解器简...
解迷透视!德州局脚本!竟然一直... 解迷透视!德州局脚本!竟然一直都是有辅助方法(有挂教程)-哔哩哔哩1、打开软件启动之后找到中间准星的...
分享透视!聚星ai辅助工具下载... 分享透视!聚星ai辅助工具下载!原来有辅助神器(有挂秘笈)-哔哩哔哩1、超多福利:超高返利,海量正版...
科普透视!werplan外开挂... 科普透视!werplan外开挂!总是真的有辅助技巧(有挂方略)-哔哩哔哩1、下载好werplan外开...