如何在JavaScript中从嵌套对象获取指定节点的URL路径字符串
实现路径可查询的URL树形结构方案
普通JS对象没有内置的父节点/路径上下文引用,直接传入websiteTree.home.categoryA.postA这类空对象无法识别它在整棵树中的位置,因此需要先对树结构做改造,给每个节点挂载路径元信息,再实现对应的查询方法。
方案1:预存路径(适合静态不变的站点树)
构建树的时候就提前把每个节点对应的路径计算好,存在非枚举属性里,查询的时候直接读取即可,性能为O(1)。
// 递归构建带路径元信息的树 function buildTree(node, parentPath = '') { const newNode = {} // 给节点挂载非枚举的__path属性,不影响普通遍历和使用 Object.defineProperty(newNode, '__path', { value: parentPath, enumerable: false }) for (const key in node) { const childPath = parentPath ? `${parentPath}/${key}` : `/${key}` newNode[key] = buildTree(node[key], childPath) } return newNode } // 原始站点树结构 const rawTree = { home: { about: {}, categoryA: { postA: {} } } } // 生成处理后的站点树 const websiteTree = buildTree(rawTree) // 特殊处理home节点,让子节点路径不会带上home前缀 Object.defineProperty(websiteTree.home, '__path', { value: '', enumerable: false }) // 路径查询方法 function getUrlPath(node) { return node.__path || '' }
测试效果:
console.log(getUrlPath(websiteTree.home.categoryA.postA)) // 输出:/categoryA/postA console.log(getUrlPath(websiteTree.home.about)) // 输出:/about console.log(getUrlPath(websiteTree.home.categoryA)) // 输出:/categoryA
方案2:动态拼接路径(适合会动态增删节点的场景)
如果站点树会频繁修改节点,预存路径需要同步更新所有子节点成本很高,可以给每个节点存父节点和自身key的引用,查询时向上遍历拼接路径。
// 递归构建带父节点、自身key引用的树 function buildTree(node, parentNode = null, key = '') { const newNode = {} Object.defineProperties(newNode, { '__parent': { value: parentNode, enumerable: false }, '__key': { value: key, enumerable: false } }) for (const childKey in node) { newNode[childKey] = buildTree(node[childKey], newNode, childKey) } return newNode } // 原始站点树结构 const rawTree = { home: { about: {}, categoryA: { postA: {} } } } const websiteTree = buildTree(rawTree) // 路径查询方法 function getUrlPath(node) { const pathSegments = [] let currentNode = node // 向上遍历直到home节点,跳过home前缀 while (currentNode?.__key && currentNode.__key !== 'home') { pathSegments.unshift(currentNode.__key) currentNode = currentNode.__parent } return pathSegments.length ? `/${pathSegments.join('/')}` : '' }
测试效果和方案1完全一致。
内容的提问来源于stack exchange,提问作者Émerson Felinto
相关产品推荐
相关产品推荐

