如何从带子节点的嵌套JSON中通过子节点ID获取所有父节点ID
Hey there! Let's figure out how to pull all parent node IDs from your nested JSON structure (where each node has a ChildAssets subarray) when you know a specific child node's ID. I'll share both recursive and iterative approaches that play nicely with your Kendo TreeView setup.
1. Recursive Search Function (Intuitive for Most Cases)
Recursion is perfect here because it mirrors the nested structure of your data. This function will traverse the tree, track the path of parent IDs, and return the full list when it finds your target child ID:
// Recursively find all parent IDs for a target child node function findParentIds(treeData, targetId, parentPath = []) { for (const node of treeData) { // Check if current node is the target - if yes, return the parent path if (node.Id === targetId) { return parentPath; } // If current node has children, recurse through them and pass updated parent path if (node.ChildAssets && node.ChildAssets.length > 0) { const result = findParentIds(node.ChildAssets, targetId, [...parentPath, node.Id]); // If we found the target in the children, return the result immediately if (result) { return result; } } } // Target not found in this branch return null; }
How It Works:
treeData: Your root JSON array (thejsonDatavariable in your Kendo code)targetId: The ID of the child node you're looking forparentPath: Tracks the chain of parent IDs as we traverse the tree (starts empty)- When we hit the target node, we return the accumulated parent IDs (ordered from top-level ancestor down to direct parent)
2. Integrate with Your Kendo TreeView Code
Here's how to drop this function into your existing loadKendoTreeView setup. I'll use your sample data to show a working example:
function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", "Name": "SampleSite1", "ChildAssets": [{ "Id": "9ee67548-f511-4d0e-8690-b7e1951ac27f", "Name": "Plant0", "ChildAssets": [{ "Id": "8678ba42-2d7a-4956-a915-415a457c0196", "Name": "Area0", "ChildAssets": [{ "Id": "36d02c55-e908-44a5-ba33-07e0125e9eed", "Name": "Unit0", "ChildAssets": [] }] }] }] }]; // Example: Find parent IDs for "Unit0" const targetChildId = "36d02c55-e908-44a5-ba33-07e0125e9eed"; const parentIds = findParentIds(jsonData, targetChildId); if (parentIds) { console.log("Parent IDs (top to bottom):", parentIds); // Output will be: ["239297d8-5993-42c0-a6ca-38dac2d8bf9f", "9ee67548-f511-4d0e-8690-b7e1951ac27f", "8678ba42-2d7a-4956-a915-415a457c0196"] } else { console.log("Target child node not found!"); } // Initialize your Kendo TreeView as usual $("#treeview").kendoTreeView({ dataSource: jsonData, dataTextField: "Name", dataChildrenField: "ChildAssets" // Add any other TreeView config here }); }
3. Iterative Alternative (For Deeply Nested Trees)
If your tree has extremely deep nesting (which could cause stack overflow with recursion), use this iterative approach with a stack instead:
// Iterative search to avoid stack overflow with deep trees function findParentIdsIterative(treeData, targetId) { // Stack stores objects with current node and its parent path const stack = treeData.map(node => ({ node, path: [] })); while (stack.length > 0) { const { node, path } = stack.pop(); if (node.Id === targetId) { return path; } // Push child nodes to stack (reverse order to maintain traversal order) if (node.ChildAssets && node.ChildAssets.length > 0) { const updatedPath = [...path, node.Id]; for (let i = node.ChildAssets.length - 1; i >= 0; i--) { stack.push({ node: node.ChildAssets[i], path: updatedPath }); } } } return null; }
Quick Tip:
If you want the parent IDs ordered from direct parent up to the top-level ancestor, just reverse the returned array:
const parentIdsReversed = parentIds ? parentIds.reverse() : null;
内容的提问来源于stack exchange,提问作者Sonu

