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

如何移除嵌套Object的键并将其转换为Object数组

Solution

Got it, let's tackle this problem where we need to convert those numeric-keyed nested objects into arrays of objects. The core idea is to recursively traverse the data structure, turning any object with numeric string keys into an array of its values, while preserving the rest of the structure.

Step 1: The Recursive Conversion Function

Here's a reusable function that handles all nested levels (like descendants and children):

// Your original data
const originalData = { 
  "1":{ 
    name: 'Main Parent', 
    descendants: { 
      "1":{ name: "Main Child 1", children: { "1":{ name: "Sub Child 1" } } }, 
      "2":{ name: "Main Child 2", children: { "1":{ name: "Sub Child 1" } } }, 
    } 
  } 
};

function convertKeyedObjectsToArrays(obj) {
  // If we're not dealing with an object, return it as-is
  if (typeof obj !== 'object' || obj === null) return obj;

  // Check if this object is a numeric-keyed collection
  const isNumericKeyed = Object.keys(obj).every(key => !isNaN(parseInt(key, 10)));

  if (isNumericKeyed) {
    // Convert to array and process each item recursively
    return Object.values(obj).map(item => convertKeyedObjectsToArrays(item));
  } else {
    // Process each property of the regular object recursively
    const processedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        processedObj[key] = convertKeyedObjectsToArrays(obj[key]);
      }
    }
    return processedObj;
  }
}

// Run the conversion
const convertedData = convertKeyedObjectsToArrays(originalData);
console.log(convertedData);

Step 2: What This Does

  • Recursive Traversal: The function goes through every level of your data structure, so it handles deep nesting automatically.
  • Numeric Key Check: For each object, it checks if all keys are numeric strings. If yes, it converts the object to an array using Object.values().
  • Preserve Structure: Regular objects (like those with name, descendants, or children properties) stay intact—only the numeric-keyed collections get turned into arrays.

Result

When you run the code, convertedData will match the array structure you're looking for:

[
  {
    "name": "Main Parent",
    "descendants": [
      {
        "name": "Main Child 1",
        "children": [
          { "name": "Sub Child 1" }
        ]
      },
      {
        "name": "Main Child 2",
        "children": [
          { "name": "Sub Child 1" }
        ]
      }
    ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:36:29