如何在JavaScript对象中查找指定ID的路径位置?
Problem Overview
You’ve got a deeply nested JavaScript object with both objects and array branches, and need to traverse every level to find the exact access path for a target ID. For example, given the ID xobmnbjxg0g_1527269346261, you want the output path to match this format: app['structure'][0]['if-children'][0]['id'].
Solution Approach
We’ll use a recursive function to crawl the entire object tree. It’ll track the current path as it goes, and return the full formatted path the moment it finds a node whose id matches your target. This handles both object properties (using key names) and array elements (using indices) smoothly.
Working Code
Here’s a complete implementation tailored to your use case:
// Target ID we're searching for const targetId = 'xobmnbjxg0g_1527269346261'; // Your nested application object var app = { "structure": [ { "id": "0", "type":"IF", "parameters": [ { "id": "xobmnbjxg0g_1527269346260", "type": "field", "value": "CV_TEST_SPOT1X" }, { "id": "2", "type": "operator", "value": "=" }, { "id": "3", "type": "field", "value": "North America" } ], "if-children": [ { "id": "xobmnbjxg0g_1527269346261", "type":"IF", "parameters": [ { "id": "1", "type": "field", "value": "CV_TEST_SPOT1" }, { "id": "2", "type": "operator", "value": "=" }, { "id": "3", "type": "field", "value": "North America" } ], "if-children":[ ], "else-children":[ ] } ], "else-children":[ { "id": "xobmnbjxg0g_1527269346262", "type":"IF", "parameters": [ { "id": "1", "type": "field", "value": "CV_TEST_SPOT1" }, { "id": "2", "type": "operator", "value": "=" }, { "id": "3", "type": "field", "value": "North America" } ], "if-children":[ { "id":"xobmnbjxg0g_152726934626X" } ], "else-children":[ { "id":"xobmnbjxg0g_152726934626Y" } ] } ] }, { "id": "xobmnbjxg0g_1527269346263", "type":"IF", "parameters": [ [ { "id": "1", "type": "field", "value": "CV_TEST_SPOT1" } ] ], "if-children": [ { "id": "xobmnbjxg0g_1527269346264", "type":"IF", "parameters": [ [ { "id": "1", "type": "field", "value": "CV_TEST_SPOT1" } ] ], "if-children":[ { "id": "xobmnbjxg0g_1527269346265", "type":"IF", "parameters": [ { "id": "1", "type": "field", "value": "CV_TEST_SPOT1" } ], "if-children":[ { "id":"xobmnbjxg0g_1527269346266" } ], "else-children":[ { "id":"xobmnbjxg0g_1527269346267" } ] } ], "else-children":[ { "id":"xobmnbjxg0g_1527269346268" } ] } ], "else-children":[ { "id":"xobmnbjxg0g_1527269346269" } ] } ] }; // Recursive function to locate the ID path function findIdPath(currentNode, targetId, currentPath = []) { // Check if current node has the target ID if (currentNode?.id === targetId) { return `app${currentPath.join('')}['id']`; } // Handle arrays: iterate over each index if (Array.isArray(currentNode)) { for (let i = 0; i < currentNode.length; i++) { const result = findIdPath(currentNode[i], targetId, [...currentPath, `[${i}]`]); if (result) return result; } } // Handle objects: iterate over each key else if (typeof currentNode === 'object' && currentNode !== null) { for (const key of Object.keys(currentNode)) { const result = findIdPath(currentNode[key], targetId, [...currentPath, `['${key}']`]); if (result) return result; } } // Return null if ID not found in this branch return null; } // Run the function and log the result const path = findIdPath(app, targetId); console.log(path); // Output: app['structure'][0]['if-children'][0]['id']
Key Details
- Recursive Crawl: The function dives into every nested object and array, building the path as it goes.
- Exact Formatting: Matches the syntax you requested (
['key']for object properties,[index]for array elements). - Early Termination: Stops traversing immediately once the target ID is found, saving unnecessary processing.
- Edge Case Handling: Works with null values, empty arrays/objects, and deeply nested structures.
Notes
- If multiple nodes share the same ID, this function returns the path to the first occurrence it finds during traversal.
- To get all matching paths instead of just the first, modify the function to collect results in an array instead of returning on the first hit.
内容的提问来源于stack exchange,提问作者lol

