js拆分数据格式

需求:

将对应所选的下拉框选中数据,与下拉选做匹配,并生成树级格式数据

数据格式为:

// 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;
  }, []);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值