1.要转的数据结构,主要根据id和pid来区分节点
{
"id": 1,
"pid": 0,
"label": "组件传值"
},
{
"id": 2,
"pid": 1,
"label": "父向子传值"
},
{
"id": 3,
"pid": 2,
"label": "prop"
},{
"id": 4,
"pid": 3,
"label": "写法"
},
{
"id": 5,
"pid": 4,
"label": "子组件"
},
{
"id": 6,
"pid": 5,
"label": "数组型:props:['value']"
},
{
"id": 7,
"pid": 5,
"label": '<img src="https://tse1-mm.cn.bing.net/th/id/OIP-C.O4vKZPMT-5--cV-C7xuP0AHaEC?w=313&h=180&c=7&r=0&o=5&pid=1.7" alt="" srcset="">'
},
{
"id": 8,
"pid": 5,
"label": "对象型:props:{value:{type:String,required:\ntrue,default:\"21\",validator(value){return ['\nsuccess','12'.'21'],}}}"
},
{
"id": 9,
"pid": 3,
"label": "用法"
},
转后的数据结构
{
"id": 3,
"pid": 2,
"label": "prop",
"children": [
{
"id": 4,
"pid": 3,
"label": "写法",
"children": [
{
"id": 5,
"pid": 4,
"label": "子组件",
"children": [
{
"id": 6,
"pid": 5,
"label": "数组型:props:['value']"
},
{
"id": 7,
"pid": 5,
"label": "<img src=\"https://tse1-mm.cn.bing.net/th/id/OIP-C.O4vKZPMT-5--cV-C7xuP0AHaEC?w=313&h=180&c=7&r=0&o=5&pid=1.7\" alt=\"\" srcset=\"\">"
},
{
"id": 8,
"pid": 5,
"label": "对象型:props:{value:{type:String,required:\ntrue,default:\"21\",validator(value){return ['\nsuccess','12'.'21'],}}}"
}
]
}
]
},
通过循环判断当前节点是否为根节点,不是根节点的话就通过getparent函数找到它的父节点,插入到父节点的children中, getparent函数通过递归深层查找每一层节点
const getobject = (arr) => {
let children = []
function getparent(arr, parent) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id == parent[0].pid) {
if (arr[i].children) {
arr[i].children.push(parent[0])
} else {
arr[i].children = parent
}
return arr
}
if (arr[i].children) {
arr[i].children = getparent(arr[i].children, parent)
}
}
return arr
}
for (let i = 0; i < arr.length; i++) {
if (arr[i].pid && arr[i].pid != 0) {
children.push(arr[i])
arr.splice(i, 1)
arr = getparent(arr, children)
children = []
i--
}
return arr
}