// 原始数据
let dataSource = [
{ id: 1, pid: 0, name: '一级菜单A' },
{ id: 2, pid: 0, name: '一级菜单B' },
{ id: 3, pid: 0, name: '一级菜单C' },
{ id: 4, pid: 1, name: '二级菜单A-A' },
{ id: 5, pid: 1, name: '二级菜单A-B' },
{ id: 6, pid: 2, name: '二级菜单B-B' },
{ id: 7, pid: 2, name: '二级菜单B-C' },
{ id: 8, pid: 6, name: '三级菜单B-B-A' },
{ id: 9, pid: 6, name: '三级菜单B-B-B' },
];
/**
* [将数组格式化为树型结构]
* @param {[type]} dataSource [原始数据]
* @param {[type]} id_key [主key]
* @param {[type]} parrentId_key [父key]
* @return {[type]} [格式化后的树形数据]
*/
const formatTreeData = (dataSource, id_key, parrentId_key) =>{
// 深度复制一份,不想用lodash的,可以用其他方法
// 深度复制是为了不想改变原数组,如果不介意,可以直接用
// const data = lodash.cloneDeep(dataSource);
const data = JSON.parse(JSON.stringify(dataSource));
data.forEach(i =>
i.children = data.filter(j => j[parrentId_key] === i[id_key])
);
return data.filter(i =>
!data.find(j => i[parrentId_key] === j[id_key])
);
};
const res = formatTreeData(dataSource, "id", "pid");
// res----
> [
> {
> "id": 1,
> "pid": 0,
> "name": "一级菜单A",
> "children": [
> {
> "id": 4,
> "pid": 1,
> "name": "二级菜单A-A",
> "children": []
> },
> {
> "id": 5,
> "pid": 1,
> "name": "二级菜单A-B",
> "children": []
> }
> ]
> },
> {
> "id": 2,
> "pid": 0,
> "name": "一级菜单B",
> "children": [
> {
> "id": 6,
> "pid": 2,
> "name": "二级菜单B-B",
> "children": [
> {
> "id": 8,
> "pid": 6,
> "name": "三级菜单B-B-A",
> "children": []
> },
> {
> "id": 9,
> "pid": 6,
> "name": "三级菜单B-B-B",
> "children": []
> }
> ]
> },
> {
> "id": 7,
> "pid": 2,
> "name": "二级菜单B-C",
> "children": []
> }
> ]
> },
> {
> "id": 3,
> "pid": 0,
> "name": "一级菜单C",
> "children": []
> }
> ]