如何编写递归函数将含嵌套数组的对象转为单元素数组的对象数组
Got it, let's work through this problem. The goal is to take an object with nested msg arrays and generate an array where each entry represents a full path from the root to a leaf node (where msg isn't an array). Every intermediate msg array in these entries will only hold the single element that leads to the corresponding leaf.
Approach
We'll use recursion to traverse each level of the nested structure:
- Base case: If the current object's
msgis not an array (we've hit a leaf), return an array containing just this object — this is one of our final result entries. - Recursive case: If the current object's
msgis an array, loop through each element in the array:- Recursively process the element to get all path entries that start with it.
- For each of those recursive results, create a deep copy of the current object, replace its
msgwith an array containing only the modified element (where the element'smsgis replaced by the recursive result'smsg). - Collect all these modified objects into a single result array to return.
Solution Code
const originalObj = { field: "parent", msg:[ { field: "child1a", msg: [ { field: "child2a", msg: "child2a-msg" }, { field: "child2b", msg: "child2b-msg" } ] }, { field: "child1b", msg: "child1b-msg" } ] }; function expandNestedObj(obj) { // Base case: we've reached a leaf node (msg is not an array) if (!Array.isArray(obj.msg)) { return [structuredClone(obj)]; } const result = []; // Iterate over each item in the current msg array for (const msgItem of obj.msg) { // Recursively expand all paths starting from this msg item const expandedChildren = expandNestedObj(msgItem); // Build a new parent object for each expanded child path for (const child of expandedChildren) { const newObj = structuredClone(obj); newObj.msg = [child]; result.push(newObj); } } return result; } // Test the function const expandedArray = expandNestedObj(originalObj); console.log(JSON.stringify(expandedArray, null, 2));
Output Breakdown
Running this code will produce exactly the target array you described:
- First entry:
{ field: "parent", msg: [ { field: "child1a", msg: [ { field: "child2a", msg: "child2a-msg" } ] } ] } - Second entry:
{ field: "parent", msg: [ { field: "child1a", msg: [ { field: "child2b", msg: "child2b-msg" } ] } ] } - Third entry:
{ field: "parent", msg: [ { field: "child1b", msg: "child1b-msg" } ] }
We use structuredClone to create deep copies of objects, which ensures we don't mutate the original data while building each unique path entry. This function works for any depth of nesting — you could add more layers of msg arrays and it would handle them correctly.
内容的提问来源于stack exchange,提问作者rnacken

