<template lang="html">
<div class=""></div>
</template>
<script>
export default {
data() {
return {
list: [
{
_id: "5debbbe8bdc6bc2150ab6ddc",
pid: 0,
title: "技术团队"
},
{
_id: "5debbc69f22ee22d0861eb29",
pid: "5debbbe8bdc6bc2150ab6ddc",
title: "移动开发"
},
{
_id: "5debbc81f22ee22d0861eb2a",
pid: "5debbbe8bdc6bc2150ab6ddc",
title: "网站开发"
},
{
_id: "5debbc8af22ee22d0861eb2b",
pid: "5debbbe8bdc6bc2150ab6ddc",
title: "销售部门"
},
{
_id: "5debbc94f22ee22d0861eb2c",
pid: 0,
title: "关于我们"
},
{
_id: "5debbca2f22ee22d0861eb2d",
pid: 0,
title: "数码"
},
{
_id: "5debbcb7f22ee22d0861eb2e",
pid: "5debbca2f22ee22d0861eb2d",
title: "笔记本电脑"
},
{
_id: "5dec6ae9aac8f231246afa84",
pid: "5debbc69f22ee22d0861eb29",
title: "前端开发"
}
]
};
},
created() {
console.log(JSON.stringify(this.getTree1(this.list), null, 2));
},
methods: {
getTree1(docs) {
let obj = {};
docs.map(item => {
obj[item._id] = item;
});
let arr = [];
docs.map(item => {
let parent = obj[item.pid];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
arr.push(item);
}
});
return arr;
},
// 递归
getTree2(docs) {
let arr = [];
docs.map(item => {
let tempArr = docs.filter(childItem => childItem.pid === item._id);
if (tempArr.length) {
this.getTree(tempArr);
item.children = tempArr;
}
if (!item.pid) {
arr.push(item);
}
});
return arr;
}
}
};
</script>
网友评论