后台给的树形层级结构,回显根据id获取名称name
/*
**❤**根据传入字符,递归获取任意层级结构数据中对应节点属性值。(层级结构数据最外层为[]或{}均可)
@onlyCode = 传入字符
@treeData = 树形结构数据
@code = 节点编码id,不传默认为value
@name = 节点名称name,不传默认为label
@childName = 内嵌数组对象集的属性名称,不传默认为children
*/
const getNameFormTree = (onlyCode, treeData, code = "value", name = "label", childName = "children") => {
let resultName = ""
if (!treeData||!onlyCode) {return ""}
const getChild = (treeData) => {
// 外层是对象的处理
if (!(treeData instanceof Array)) {
if (onlyCode==treeData[code] ) { resultName = treeData[name]; return resultName }
if (treeData[childName] && treeData[childName].length > 0) { getChild(treeData[childName]) }
}
// 最外层是数组的处理
for (let i = 0; i < treeData.length; i++) {
if (onlyCode == treeData[i][code]) { resultName = treeData[i][name]; break }else {resultName = ""}
if (treeData[i][childName] && treeData[i][childName].length > 0) {
getChild(treeData[i][childName])
}
}
return resultName
}
return getChild(treeData)
}
使用时:
let tree = [{
children: [{
id: 1,
label: '一级 1',
children: [{
id: 4,
label: '二级 1-1',
children: [{
id: 9,
label: '三级 1-1-1'
}, {
id: 10,
label: '三级 1-1-2'
}]
}]
}, {
id: 2,
label: '一级 2',
children: [{
id: 5,
label: '二级 2-1'
}, {
id: 6,
label: '二级 2-2'
}]
}, {
id: 3,
label: '一级 3',
children: [{
id: 7,
label: '二级 3-1'
}, {
id: 8,
label: '二级 3-2'
}]
}],
id :1001,label:"主级"
}]
let data = getNameFormTree(10, tree,"id")
console.log(data) // 三级 1-1-2