首页 新闻 会员 周边

求助:将js数组对象转换为三级联动数据格式并去重排序!!!

0
悬赏园豆:120 [已解决问题] 解决于 2022-05-30 11:19

原数组对象格式:

const data = [
        {
          sgbh: "20200701003",
          qywz: "分离器1",
          ch: "1",
          cwmc: "T2l4雷四段",
        },
        {
          sgbh: "20200701003",
          qywz: "分离器1",
          ch: "1",
          cwmc: "T2l4雷三段",
        },
        {
          sgbh: "20200701003",
          qywz: "分离器3",
          ch: "2",
          cwmc: "T2l4雷四段",
        },
      ]

处理后的数据格式:

[
        {
          value: '分离器1',
          label: '分离器1',
          children: [
            {
              value: '1',
              label: '1',
              children: [
                {
                  value: 'T2l4雷三段', 
                  label: 'T2l4雷三段'
                },
                {
                  value: 'T2l4雷四段', 
                  label: 'T2l4雷四段'
                }
              ]
            }
          ]
        },
        {
          value: '分离器3', 
          label: '分离器3', 
          children: [
            {
              value: '2',
              label: '2',
              children: [
                {
                  value: 'T2l4雷四段', 
                  label: 'T2l4雷四段'
                }
              ]
            }
          ]
        }
      ]
wanxinwl的主页 wanxinwl | 初学一级 | 园豆:94
提问于:2022-05-15 22:59
< >
分享
最佳答案
0
// 根据指定 key 计算分组
function groupBy(list, groupField) {
  const groupedData = list.reduce((result, item) => {
    const groupKey = item[groupField];
    if (!result[groupKey]) {
      result[groupKey] = [];
    }
    result[groupKey].push(item);
    return result;
  }, {});
  return groupedData;
}

// 通用转换逻辑,将分组数据拆解为数组
function convertGroup2Arr(groupedData, processChildren) {
  return Object.keys(groupedData).map((key) => {
    return {
      label: key,
      value: key,
      children: processChildren(groupedData[key]),
    };
  });
}

// 这是你具体的业务逻辑
function process(data) {
  // 第一次按照 qywz 进行分组
  const groupedData = groupBy(data, 'qywz');
  return convertGroup2Arr(groupedData, (data2) => {
    // 第二次按照 ch 进行分组
    const groupedData2 = groupBy(data2, 'ch');
    return convertGroup2Arr(groupedData2, (data3) => {
      // 第三次按照 cwmc 进行分组
      const groupedData3 = groupBy(data3, 'cwmc');
      return convertGroup2Arr(groupedData3, () => []);
    });
  });
}

const data = [
  {
    sgbh: '20200701003',
    qywz: '分离器1',
    ch: '1',
    cwmc: 'T2l4雷四段',
  },
  {
    sgbh: '20200701003',
    qywz: '分离器1',
    ch: '1',
    cwmc: 'T2l4雷三段',
  },
  {
    sgbh: '20200701003',
    qywz: '分离器3',
    ch: '2',
    cwmc: 'T2l4雷四段',
  },
];

process(data);

供参考~

收获园豆:120
幻天芒 | 高人七级 |园豆:37175 | 2022-05-16 10:20

老哥,我看最后一级有个空的children项,可以去掉吗

wanxinwl | 园豆:94 (初学一级) | 2022-05-16 15:36

@wanxinwl: 思路就是这样,你可以自己加判断处理下最后一级。

幻天芒 | 园豆:37175 (高人七级) | 2022-05-26 22:20
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册