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

JavaScript嵌套对象数组转换为指定结构对象的实现求助

Convert Nested Object Array to Target Nested Object Structure

I get it, converting that nested array into the ID-keyed object structure can be tricky with recursion if you don't nail down the base case correctly. Let's walk through a working solution step by step.

The Problem Recap

You have a nested array of objects where each item has id, name, and a child array. You want to transform this into a nested object where each level uses the item's id as the key, and the deepest nodes map to an empty string.

Solution Code (JavaScript)

Here's a recursive function that does exactly what you need:

function convertToNestedObject(arr) {
  const result = {};
  arr.forEach(item => {
    // If there are no children, map the ID to an empty string
    if (item.child.length === 0) {
      result[item.id] = "";
    } else {
      // Recursively process the child array and assign it to the current ID key
      result[item.id] = convertToNestedObject(item.child);
    }
  });
  return result;
}

// Example usage with your input array
const originalArray = [
  {
    "id": "31a3sd2f1a3ds21f",
    "name": "Energy device",
    "child": [
      {
        "id": "65sa4d65a4sdf654adsf",
        "name": "Device 2",
        "child": [
          {
            "id": "65a4d65ad4s54adsf",
            "name": "Device 3",
            "child": []
          }
        ]
      }
    ]
  },
  {
    "id": "6as54d54as5f",
    "name": "Energy device 2",
    "child": [
      {
        "id": "9a8s7df98a78sdf",
        "name": "Device 4",
        "child": [
          {
            "id": "65a4d65ad4s54adsf",
            "name": "Device 5",
            "child": []
          }
        ]
      },
      {
        "id": "65asd54as5f4",
        "name": "Device 5-1",
        "child": []
      }
    ]
  }
];

const targetObject = convertToNestedObject(originalArray);
console.log(JSON.stringify(targetObject, null, 2));

How It Works

  • Base Case: When an item has no children (item.child.length === 0), we add its id to the result object with an empty string as the value.
  • Recursive Case: For items with children, we recursively call convertToNestedObject on the child array and assign the returned nested object to the current item's id key.
  • Iteration: We loop through each item in the input array (or child array) and build out the result object level by level.

Output

Running this code will produce exactly the target structure you wanted:

{
  "31a3sd2f1a3ds21f": {
    "65sa4d65a4sdf654adsf": {
      "65a4d65ad4s54adsf": ""
    }
  },
  "6as54d54as5f": {
    "9a8s7df98a78sdf": {
      "65a4d65ad4s54adsf": ""
    },
    "65asd54as5f4": ""
  }
}

内容的提问来源于stack exchange,提问作者Mohammad Nasir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 18:28:13