如何为递归转换的树形节点添加完整父节点路径path属性?
递归树形数据新增完整路径(path)属性的修改方案
核心修改思路
递归过程中传递父节点的完整路径,每次拼接当前节点的标识字段(如你示例中的cardShop这类key值),生成当前节点的path属性。
针对扁平数据转树形的修改代码
假设你原来的扁平转树形代码是类似这样:
// 原代码(示例) function buildTree(data, parentId = null) { return data .filter(item => item.parentId === parentId) .map(item => ({ ...item, children: buildTree(data, item.id) })); }
修改后的代码:
function buildTreeWithPath(data, parentId = null, parentPath = '') { return data .filter(item => item.parentId === parentId) .map(item => { // 根据父路径拼接当前节点的完整path const currentPath = parentPath ? `${parentPath}.${item.key}` : item.key; return { ...item, path: currentPath, // 递归调用时传递当前节点的path作为子节点的父路径 children: buildTreeWithPath(data, item.id, currentPath) }; }); }
针对已有树形结构直接新增path的修改代码
如果你的原始数据已经是树形结构,只需遍历添加path:
function addPathToTree(tree, parentPath = '') { return tree.map(node => { const currentPath = parentPath ? `${parentPath}.${node.key}` : node.key; return { ...node, path: currentPath, // 递归处理子节点,传递当前path作为父路径 children: node.children ? addPathToTree(node.children, currentPath) : [] }; }); }
示例验证
输入数据(扁平示例)
const flatData = [ { id: 1, key: 'cardShop', parentId: null }, { id: 2, key: 'cardData', parentId: 1 }, { id: 3, key: 'cardTitle', parentId: 2 }, { id: 4, key: 'cardDesc', parentId: 2 }, { id: 5, key: 'cardPrice', parentId: 1 } ];
调用后输出
[ { "id": 1, "key": "cardShop", "parentId": null, "path": "cardShop", "children": [ { "id": 2, "key": "cardData", "parentId": 1, "path": "cardShop.cardData", "children": [ { "id": 3, "key": "cardTitle", "parentId": 2, "path": "cardShop.cardData.cardTitle", "children": [] }, { "id": 4, "key": "cardDesc", "parentId": 2, "path": "cardShop.cardData.cardDesc", "children": [] } ] }, { "id": 5, "key": "cardPrice", "parentId": 1, "path": "cardShop.cardPrice", "children": [] } ] } ]
注意事项
- 确保你的节点中有唯一标识路径的字段(示例中用的是
key,如果你的字段名是name或其他,替换成对应字段即可) - 如果根节点不需要前缀,初始
parentPath设为空字符串即可,根节点的path就是自身的key值
内容的提问来源于stack exchange,提问作者K.S
相关产品推荐
相关产品推荐

