在网上找了很久,没有解决方案,最后画了一天时间写了这个方法。。。
业务中经常会遇到生成树形结构的需求,很多时候是通过在数据库中保存父节点id的方式,比如多级菜单,但最近碰到了一钟需求,数据量很大,比如:
市,县,乡,村,组,这种类型的多条数据,需要再前端生成树形结构。
县 | 乡 | 村 | 组 |
---|---|---|---|
某1县 | 某1乡 | 某1 村 | 某1组 |
某1县 | 某2乡 | 某2 村 | 某2组 |
某1县 | 某3乡 | 某3 村 | 某3组 |
某1县 | 某4乡 | 某4 村 | 某4组 |
某1县 | 某5乡 | 某5 村 | 某5组 |
代码
通过一层层的判断完成,
/**
* 平行数据转为树形结构数据
* 通过一层层进入判断完成;
* @param {*} array 数组数据
* @param {*} fields 按顺序的field,比如['县','乡','村','组']
*/
function myArrayToTree(array, fields) {
var tree = []
var lastItem
for (var item of array) {
for (var [index, value] of fields.entries()) {
if (index === 0) {
if (getLabelObject(tree, item[value])) {
lastItem = getLabelObject(tree, item[value])
} else {
tree.push({
label: item[value],
icon: 'el-icon-folder'
})
lastItem = tree[tree.length - 1]
}
} else if (index !== fields.length - 1) {
if (!Array.isArray(lastItem.children)) {
lastItem.children = []
}
if (getLabelObject(lastItem.children, item[value])) {
lastItem = getLabelObject(lastItem.children, item[value])
} else {
lastItem.children.push({
label: item[value],
icon: 'el-icon-folder'
})
lastItem = lastItem.children[lastItem.children.length - 1]
}
} else {
// 最后一级
if (!Array.isArray(lastItem.children)) {
lastItem.children = []
}
if (getLabelObject(lastItem.children, item[value])) {
lastItem = getLabelObject(lastItem.children, item[value])
} else {
lastItem.children.push({
id: item[value],
label: item[value],
icon: 'el-icon-location-outline'
})
lastItem = lastItem.children[lastItem.children.length - 1]
}
}
}
}
return tree
}
// 获取数组中包含对应lable值的对象
function getLabelObject(array, identityString) {
let object = false
for (var item of array) {
if (item.label === identityString) {
object = item
break
}
}
return object
}