js实现树形结构数据中根据指定参数查询其所有父级节点
JavaScipt
2025-10-31 19:27:12
树形结构数据在前端开发中常见于菜单、省市区信息中使用,那么对于这些树形结构数据的使用我们要如何更便捷的操作呢?
本篇文章内容介绍在前端开发中如何根据指定参数进行查询其所有父级节点信息。
一、创建查询公用方法
/**
* 在树形数据中根据指定参数查找所有父级节点
* @param {Array} tree 树形数据
* @param {*} targetValue 要查找的目标值
* @param {Object} options 配置项
* @param {string} options.valueKey 节点值字段名,默认 'value'
* @param {string} options.childrenKey 子节点字段名,默认 'children'
* @param {boolean} options.includeCurrent 是否包含当前节点,默认 false
* @returns {Array} 父级节点数组,从根节点到直接父节点
*/
function findParents(tree, targetValue, options = {}) {
const {
valueKey = 'value',
childrenKey = 'children',
includeCurrent = false
} = options;
let result = [];
function traverse(nodes, path) {
for (const node of nodes) {
// 创建当前路径(包含当前节点)
const currentPath = [...path, node];
// 如果找到目标节点
if (node[valueKey] === targetValue) {
if (includeCurrent) {
result = currentPath; // 包含当前节点
} else {
result = path; // 不包含当前节点,只包含父级
}
return true; // 找到目标,停止遍历
}
// 如果有子节点,递归查找
if (node[childrenKey] && node[childrenKey].length > 0) {
if (traverse(node[childrenKey], currentPath)) {
return true; // 在子树中找到目标,直接返回
}
}
}
return false;
}
traverse(tree, []);
return result;
}二、页面中使用findParents方法
const treeData = [
{
id: 1,
name: '北京市',
children: [
{
id: 2,
name: '朝阳区',
children: [
{ id: 3, name: '三里屯' },
{ id: 4, name: '国贸' }
]
},
{
id: 5,
name: '海淀区',
children: [
{ id: 6, name: '中关村' }
]
}
]
}
];
// 查找 id 为 3 的节点的所有父级
const parents = findParents(treeData, 3, {
valueKey: 'id',
includeCurrent: false
});
console.log(parents);
// 输出: [
// { id: 1, name: '北京市', children: [...] },
// { id: 2, name: '朝阳区', children: [...] }
// ]注意项:
使用中需要注意节点值字段名和子节点值字段名是否为value和children,若不是需进行单独设置。
六月初字帖坊小程序
你想要的字帖模板及工具,这里都有!
899篇文章
29人已阅读
六月初