需求:
将对应所选的下拉框选中数据,与下拉选做匹配,并生成树级格式数据
数据格式为:
// select 框中数据格式
const s = [{0: 104, 1: 100, 2: 101}]
// 下拉框数据为
const arr = [
{id:101,ontologyId:5,name:'11'},
{id:102,ontologyId:5,name:'11'},
{id:103,ontologyId:5,name:'11'},
{id:104,ontologyId:6,name:'11'},
{id:105,ontologyId:7,name:'11'},
{id:106,ontologyId:8,name:'11'},
]
// 需要拆分为
const groupedData = [
{ ontologyId:5,
{id:101,name:'11'},
{id:102,name:'11'},
{id:103,name:'11'},
},
{ ontologyId:6,
{id:104,name:'11'},
},
]
实现:
// 1:首先对下拉选中的数组进行改造
s.forEach(item => {
nS.push(item)
});
// nS: [101,102,103,104]
// 2: 把拉下选中,选中的数据筛选出来
labelList.value = arr.filter(item => nS.includes(item.id))
// labelList.value 该数组为筛选后的下来选数据
//[
// {id:101,ontologyId:5,name:'11'},
// {id:102,ontologyId:5,name:'11'},
// {id:103,ontologyId:5,name:'11'},
// {id:104,ontologyId:6,name:'11'},
// 3:进行拼接数据
const groupedData = labelList.value.reduce((acc, item) => {
// 查找是否已存在该 ontologyId 的分组
const group = acc.find(g => g.ontologyId === item.ontologyId);
if (group) {
// 如果存在,将 id 添加到对应的数组中
group.id.push(item.id);
} else {
// 如果不存在,创建新的分组
acc.push({
ontologyId: item.ontologyId,
id: [item.id]
});
}
return acc;
}, []);