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

相关内容

热门资讯

让我来分享经验!德普辅助软件,... 让我来分享经验!德普辅助软件,wepoker黑侠辅助器正版下载,揭秘攻略(有挂攻略);1分钟了解详细...
透视透视"aapok... 《透视透视"aapoker怎么控制牌"详细辅助分享教程(都是有挂)》 aapoker怎么控制牌软件透...
科技分享!德普之星有透视辅助吗... 《科技分享!德普之星有透视辅助吗,wpk辅助软件,切实教程(有挂教程)》 德普之星有透视辅助吗软件透...
辅助透视"wepok... 辅助透视"wepoker辅助透视软件"详细辅助德州论坛(切实有挂);wepoker辅助透视软件软件透...
一分钟教你!wepoker私人... 一分钟教你!wepoker私人局辅助挂,来玩app 德州 辅助,曝光教程(有挂攻略);wepoker...
透视辅助"wepok... 1、透视辅助"wepoker可以透视码"详细辅助德州论坛(从来真的是有挂)(UU poker、wep...
盘点一款!安装不了wepoke... 此外,数据分析德州(wepoker插件程序激活码)辅助神器app还具备辅助透视行为开挂功能,通过对客...
透视黑科技"购买we... 《透视黑科技"购买wepoker模拟器"详细辅助规律教程(素来是有挂)》 购买wepoker模拟器软...
推荐一款!hhpkoer辅助器... 推荐一款!hhpkoer辅助器视频,wepoker破解版内购,AI教程(有挂技巧);致您一封信;亲爱...
透视总结"wepok... 透视总结"wepoker透视脚本视频"详细辅助力荐教程(原生存在有挂);建议优先通过wepoker透...