案列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;
};