最近做一個(gè)樹形表格,從數(shù)據(jù)庫讀出來給前端后餐胀,用插件老是有一些顯示的錯(cuò)誤哟楷,可能是因?yàn)椴寮€需要數(shù)據(jù)按順序排好,so就有了這種轉(zhuǎn)樹再轉(zhuǎn)回來的奇葩想法
var data = [{
"Id": 1,
"Key": "params",
"Value": "",
"Pid": -1
}, {
"Id": 3,
"Key": "filter",
"Value": "",
"Pid": 1
}, {
"Id": 2,
"Key": "method",
"Value": "Post|Get",
"Pid": 1
}, {
"Id": 4,
"Key": "$and",
"Value": "",
"Pid": 3
}, {
"Id": 6,
"Key": "it:pt",
"Value": "@it:pt",
"Pid": 4
}, {
"Id": 5,
"Key": "bo:well",
"Value": "@bo:well",
"Pid": 4
}]
console.log(readTree(getTree(data, -1)[0], []))
//轉(zhuǎn)成樹
function getTree(data, Pid) {
let result = []
let temp
for (let i = 0; i < data.length; i++) {
if (data[i].Pid == Pid) {
temp = getTree(data, data[i].Id)
if (temp.length > 0) {
data[i].children = temp
}
result.push(data[i])
}
}
return result
}
//樹再轉(zhuǎn)回來
function readTree(data, val) {
val.push({
Id: data.Id,
Key: data.Key,
Value: data.Value,
Pid: data.Pid
})
if (data.children) {
for (let i = 0; i < data.children.length; i++) {
readTree(data.children[i], val)
}
return val
}
}
[ { Id: 1, Key: 'params', Value: '', Pid: -1 },
{ Id: 3, Key: 'filter', Value: '', Pid: 1 },
{ Id: 4, Key: '$and', Value: '', Pid: 3 },
{ Id: 6, Key: 'it:pt', Value: '@it:pt', Pid: 4 },
{ Id: 5, Key: 'bo:well', Value: '@bo:well', Pid: 4 },
{ Id: 2, Key: 'method', Value: 'Post|Get', Pid: 1 } ]