Js 数组与树状结构相互转换
示例数据
[
{
"importProductNo":null,
"periodTemplateId":null,
"importButaoId":"4a60be081644438e89ebf8e3e426e3ba",
"importButaoPid":"e723aed3e58d49e088edb732bfe20061",
"periodButaoId":null,
"periodButaoPid":null,
"butaoNo":"butao002",
"butaoName":"电机",
"checked":null,
"title":"电机"
},
{
"importProductNo":null,
"periodTemplateId":null,
"importButaoId":"930d368fccbe455abf45cfec89d440d0",
"importButaoPid":"e723aed3e58d49e088edb732bfe20061",
"periodButaoId":null,
"periodButaoPid":null,
"butaoNo":"butao003",
"butaoName":"叶片",
"checked":null,
"title":"叶片"
},
{
"importProductNo":null,
"periodTemplateId":null,
"importButaoId":"e723aed3e58d49e088edb732bfe20061",
"importButaoPid":null,
"periodButaoId":null,
"periodButaoPid":null,
"butaoNo":"butao001",
"butaoName":"机组总装配",
"checked":null,
"title":"机组总装配"
}
]
2、数组转树形结构
baseToTree(data) {
let result = []
if (!Array.isArray(data)) {
return result
}
data.forEach((item) => {
delete item.children
})
let map = {
}
data.forEach((item) => {
map[item.importButaoId] = item
})
data.forEach((item) => {
let parent = map[item.importButaoPid]
if (parent) {
;(parent.children || (parent.children = [])).push(item)
} else {
result.push(item)
}
})
return result
},
3、树形结构转数组
baseToArr(data) {
const result = []
data.forEach((item) => {
const loop = (data) => {
result.push(data)
let child = data.children
if (child) {
for (let i = 0; i < child.length; i++) {
loop(child[i])
}
}
}
loop(item)
})
return result
},
转自:https://www.cnblogs.com/psmart/p/16205972.html