扁平数据转tree

案列1 

let arr = [{ id: 1, name: '部门1', pid: 0 },
{ id: 2, name: '部门2', pid: 1 },
{ id: 3, name: '部门3', pid: 1 },
{ id: 4, name: '部门4', pid: 3 },
{ id: 5, name: '部门5', pid: 4 }];
const idMap = arr.reduce((sum, item, idx) => {
    sum[item.id] = idx;
    return sum;
}, {});
const res = [];
arr.forEach(item => {
    const { pid } = item;
    if (pid) {
        const idx=idMap[pid];
        arr[idx].children === undefined && (arr[idx].children = []);
        arr[idx].children.push(item)
    } else {
        res.push(item)
    }
})

案列2 


const data=[{"code":"2010100","dimMemberParent":"2010000","name":"集客综合实体自有渠道","dimPath":"/2000000/2010000/2010100","nm":"集团自有,集团渠道,集客综合实体自有渠道"},{"code":"2010400","dimMemberParent":"2010000","name":"大客户直销自有渠道","dimPath":"/2000000/2010000/2010400","nm":"集团自有,集团渠道,大客户直销自有渠道"},{"code":"4110500","dimMemberParent":"4110000","name":"校园直销自有渠道","dimPath":"/4000000/4110000/4110500","nm":"社会渠道,校园直销自有渠道,校园公众营销"},{"code":"4110600","dimMemberParent":"4110000","name":"校园实体自有渠道","dimPath":"/4000000/4110000/4110600","nm":"校园实体自有渠道,校园公众营销,社会渠道"}]

const main = (data) => {
    let res = [];
    data.forEach(it => {
        const paths = it.dimPath.split('/').slice(1, -1);
        const nm = it.nm.split(',').slice(0, -1);
        let parent = res;
        let dimPath = dimPathName = ''
        paths.forEach((path, idx) => {
            dimPath += '/' + path;
            dimPathName += '/' + nm[idx];
            parent = parent.find(it => it.dimPath == dimPath) || (parent.push({
                code: paths[idx],
                dimMemberParent: paths[idx - 1] || '',
                dimPath,
                name: nm[idx],
                dimPathName,
                children: []
            }), parent[parent.length - 1])
            parent = parent.children;
        });
        parent.push(it);
    });
    return res;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值