求助:将js数组对象转换为三级联动数据格式并去重排序!!!
原数组对象格式:
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雷四段'
}
]
}
]
}
]
回答
// 根据指定 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);
供参考~