You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写递归函数将含嵌套数组的对象转为单元素数组的对象数组

Recursively Expand Nested Object into Array of Path-specific Objects

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:

  1. Base case: If the current object's msg is not an array (we've hit a leaf), return an array containing just this object — this is one of our final result entries.
  2. Recursive case: If the current object's msg is 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 msg with an array containing only the modified element (where the element's msg is replaced by the recursive result's msg).
    • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:39:11