如何移除嵌套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, orchildrenproperties) 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
相关产品推荐
相关产品推荐

