如何通过Sitecore GraphQL构建树结构:获取后代与同级节点
获取后代节点(Descendants)
要获取某个节点的所有后代(包含所有层级的子节点、孙节点等),可以基于已有的children属性通过递归遍历实现:
核心逻辑
先收集当前节点的一级子节点,再递归遍历每个子节点,将它们的后代合并到结果列表中,最终得到完整的后代集合。
伪代码实现(JavaScript)
function getDescendants(node) { // 初始化后代列表为当前节点的一级子节点 let descendants = [...node.children]; // 递归处理每个子节点,合并其后代 node.children.forEach(child => { descendants = descendants.concat(getDescendants(child)); }); return descendants; }
伪代码实现(Python)
def get_descendants(node): descendants = list(node.children) for child in node.children: descendants.extend(get_descendants(child)) return descendants
示例验证
对应你的树结构:
- 调用
getDescendants(Parent 1)返回[Child 1.1, Child 1.2, Child 1.2.1, Child 1.2.1.1] - 调用
getDescendants(Child 1.2)返回[Child 1.2.1, Child 1.2.1.1]
如果需要限制后代深度(比如只获取到孙节点),可以添加depth参数控制递归终止:
function getDescendants(node, depth = Infinity) { if (depth <= 0) return []; let descendants = [...node.children]; node.children.forEach(child => { descendants = descendants.concat(getDescendants(child, depth - 1)); }); return descendants; }
获取同级节点(Siblings)
同级节点指与当前节点共享同一父节点的其他节点,核心是利用parent属性过滤父节点的子节点:
核心逻辑
- 若当前节点是根节点(无
parent),则无同级节点,返回空列表 - 否则,从父节点的
children列表中排除当前节点本身,剩余节点即为同级节点
伪代码实现(JavaScript)
function getSiblings(node) { if (!node.parent) return []; // 过滤父节点的子节点,排除当前节点 return node.parent.children.filter(sibling => sibling !== node); }
伪代码实现(Python)
def get_siblings(node): if not node.parent: return [] return [sibling for sibling in node.parent.children if sibling != node]
注意事项
- 如果节点有唯一标识(如
id),建议用标识替代引用比较(比如sibling.id !== node.id),避免因对象引用问题导致错误 - 若
children是只读集合,需先转换为可操作的数组/列表再进行过滤
示例验证
对应你的树结构:
- 调用
getSiblings(Child 1.1)返回[Child 1.2] - 调用
getSiblings(Parent 1)返回[Parent 2] - 调用
getSiblings(Root)返回[]
内容的提问来源于stack exchange,提问作者Anthony Fernandes
相关产品推荐
相关产品推荐

