根据传入字符,递归获取任意层级结构数据中对应节点属性值。

后台给的树形层级结构,回显根据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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值