需要转换为树形的数组
var data = [
{
"orderById":null,
"platformCommissionProportion":1,
"name":"添加剂",
"pid":13,
"id":26,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"药食同源",
"pid":13,
"id":25,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"特殊食品",
"pid":13,
"id":24,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"进口食品",
"pid":13,
"id":23,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"新资源食品",
"pid":13,
"id":22,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"绿色有机",
"pid":13,
"id":21,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"食品检验检测",
"pid":12,
"id":20,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"标签审核",
"pid":11,
"id":19,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"法律服务",
"pid":3,
"id":18,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"案件咨询",
"pid":3,
"id":17,
"state":"1"
},
{
"orderById":null,
"platformCommissionProportion":1,
"name":"食品餐饮许可",
"pid":2,
"id":16,
"state":"1"
}
]
转换方法
/**
* 树形数据转换
* @param {*} data
* @param {*} id
* @param {*} pid
*/
export function treeDataTranslate (data, id = 'id', pid = 'pid') {
var res = []
var temp = {}
for (var i = 0; i < data.length; i++) {
temp[data[i][id]] = data[i]
}
for (var k = 0; k < data.length; k++) {
if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
if (!temp[data[k][pid]]['children']) {
temp[data[k][pid]]['children'] = []
}
if (!temp[data[k][pid]]['_level']) {
temp[data[k][pid]]['_level'] = 1
}
data[k]['_level'] = temp[data[k][pid]]._level + 1
temp[data[k][pid]]['children'].push(data[k])
} else {
res.push(data[k])
}
}
return res
}
使用方法
// 引入上方的方法
import { treeDataTranslate } from '@/utils/myUtils'
treeDataTranslate(data)