HTML点击对象key值获取路径

问题:
公司遇到了这样一个业务,需要将JSON对象输出到html页面中,点击属性值,并展示这个对象的可访问路径
在这里插入图片描述
网上没有找到相关的解决方案,索性自己写了一个

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #container {
            white-space: pre;
        }
        #container  a {
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div id="container"></div>
    <input type="text" id="input">

    <script>
         let obj = {
            g: [
                {
                    233: 1

                },
                {
                    s: 2
                },
                {
                    s123: 2
                }
            
            ],
             a: 'zs',
             b: {
                 c: 12,
                 d: [1, 2, 3],
                 e: {
                     f: 'fff',
                     a: 'deepa'
                 }
             }, 

        } 


        // 递归遍历对象里面所有key对应的path,  key可以重复。 1为指针指向
        var tempKeyPaths = {}
        /* { 
           a:  [ 1, 'path1', 'path2' ]
         } */

        function deepAddPath(obj, parentPath = '') {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                  //  获取当前属性路径
                    const currentPath = parentPath + '.' + key
                    // 当前元素非数组
                    if (!Array.isArray(obj)) {
                        // 判断当前属性,是否设置过存储路径
                        if (Array.isArray(tempKeyPaths[key])) {
                            tempKeyPaths[key].push(currentPath)
                        } else {
                            // 
                            tempKeyPaths[key] = [1, currentPath]
                        }
                    }
                    // 子元素是一个对象
                    if (typeof obj[key] == 'object' && typeof obj[key] !== null) {
                        deepAddPath(obj[key], currentPath)
                    }
                }
            }
            return obj
        }
        
        const res = deepAddPath(JSON.parse(JSON.stringify(obj)))
        // 正则拼接,匹配对象key值    /(a | b | c):/
        const temp = Object.keys(tempKeyPaths).join('|')
        const pattern1 = new RegExp('\"\(' + temp + '\)\":', "gi");
        console.log(pattern1)
        // 序列化对象,制表符进行缩进
        const ss = JSON.stringify(res, null, '\t').replace(pattern1, function (key) {
            // 去除:号
            key = key.slice(0, -1)
            // 去除序列化后的“”, 获取属性指针表
            let tempArray = tempKeyPaths[key.slice(1, -1)];
            // tempArray[0] 为属性指针指向
            let curentVal = tempArray[tempArray[0]]
            // 转换数字属性为中括号访问, obj.123 => obj[123]
            curentVal = curentVal.replace(/\.\d+/g, function (path) {
                path = path.slice(1)
                return  `['${path}']`
            })  
            // 指针递增
            tempArray[0]++
            return `<a href="javascript:void(0)"  data-path="${curentVal}" class="pathMap">${key}</a>:`
        })

        let container = document.querySelector('#container')
        let input = document.querySelector('#input')
        container.innerHTML = ss

        container.addEventListener("click", function (e) {
            if (e.target.tagName == "A") {
                const path = 'obj' + e.target.getAttribute('data-path')
               // console.log(path)
                input.value = path
            }
        });
        
    </script>
</body>
</html>
el-tree获取路径信息的方法如下: 1. 使用el-tree的node-key属性来设置每个节点的唯一标识符。 2. 使用el-tree的current-node-key属性来设置当前选中的节点的唯一标识符。 3. 使用el-tree的getCheckedNodes方法获取所有选中的节点。 4. 使用el-tree的getNode方法根据节点的唯一标识符获取节点对象。 5. 使用递归的方式获取当前选中节点的所有父节点,直到根节点为止。 6. 将获取到的父节点按照路径顺序进行拼接,即可得到路径信息。 以下是一个示例代码: ```html <template> <el-tree :data="treeData" :node-key="nodeKey" :current-node-key="currentNodeKey" @node-click="handleNodeClick" ></el-tree> </template> <script> export default { data() { return { treeData: [ { id: 1, label: 'Node 1', children: [ { id: 2, label: 'Node 1-1', children: [ { id: 3, label: 'Node 1-1-1', }, ], }, { id: 4, label: 'Node 1-2', }, ], }, { id: 5, label: 'Node 2', }, ], nodeKey: 'id', currentNodeKey: null, }; }, methods: { handleNodeClick(data) { this.currentNodeKey = data[this.nodeKey]; const path = this.getPath(data); console.log('Path:', path); }, getPath(node) { const path = []; this.getParentPath(node, path); return path.reverse().join(' > '); }, getParentPath(node, path) { if (node) { path.push(node.label); const parentNode = this.$refs.tree.getNode(node[this.nodeKey]); this.getParentPath(parentNode.parent, path); } }, }, }; </script> ``` 在上述示例中,我们使用了el-tree组件来展示树形结构的数据,并通过设置node-key属性来指定节点的唯一标识符。在点击节点时,我们通过handleNodeClick方法获取当前选中的节点,并调用getPath方法来获取路径信息。getPath方法使用递归的方式获取当前节点的所有父节点,并将路径信息按照顺序进行拼接。最后,我们将路径信息打印到控制台上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值