验证中...
片段 1 片段 2
tree2flatten.js
原始数据 复制代码
const tree = [
{
title: '标题1'
},
{
title: '标题2',
children: [
{
title: '标题2-1'
},
{
title: '标题2-2'
}
]
},
{
title: '标题3',
children: [
{
title: '标题3-1' ,
children: [
{
title: '标题3-1-1'
}
]
}
]
}
]
/**
* 树形菜单转化成一维数组(无级联关系)
* @param {Array} tree
*/
function tree2flatten (tree) {
let arr = [];
tree.forEach((item) => {
if (item.children) {
arr = arr.concat(tree2flatten(item.children))
}
// delete item.children;
arr.push(item);
});
return arr;
}
flatten2Tree.js
原始数据 复制代码
const data = [
{ name: '顶层菜单', id: '20', pid: '1' },
{ name: '菜单1', id: '21', pid: '20' },
{ name: '菜单2', id: '22', pid: '20' },
{ name: '菜单3', id: '23', pid: '20' },
{ name: '菜单1-1', id: '24', pid: '21' },
{ name: '菜单1-2', id: '25', pid: '21' },
{ name: '菜单2-1', id: '26', pid: '22' },
{ name: '菜单3-1', id: '27', pid: '23' },
{ name: '菜单3-2', id: '28', pid: '23' },
{ name: '菜单3-1-1', id: '29', pid: '27' },
{ name: '菜单3-1-1-1', id: '30', pid: '29' },
{ name: '菜单3-1-1-2', id: '31', pid: '29' },
{ name: '菜单3-1-1-2-1', id: '32', pid: '31' },
]
/**
* 无限层级关系数组转化成树形菜单数组
* @param {Array} data 有层级关系的数组
*/
function flatten2Tree (data) {
const result = [];
const mapIds = data.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {})
for (let item of data) {
let parent = mapIds[item.pid];
if (parent) {
parent.children = (parent.children || []).concat(item);
} else {
result.push(item);
}
}
return result;
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助