如何将可变嵌套数组转换为指定结构的Object?
Hey there, let's tackle this problem of turning that nested array structure (where each entry is a [key, value] pair, and values can be either primitives or another nested array of the same format) into a clean, standard JavaScript object. This solution will work even when the nested structure changes, since it's built to handle any depth of nesting.
Solution Code
Here's a recursive function that does exactly what you need:
function convertArrayToObject(arr) { const result = {}; for (const [key, value] of arr) { // Check if the value is another nested [key, value] array if (Array.isArray(value) && value.every(item => Array.isArray(item) && item.length === 2)) { result[key] = convertArrayToObject(value); } else { // Convert string numbers to actual numbers (like "1" → 1) to match your desired output const processedValue = !isNaN(value) && typeof value === 'string' ? Number(value) : value; result[key] = processedValue; } } return result; } // Test it with your input array const input = [["seller" , [["id" , "1"], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]; const output = convertArrayToObject(input); // Log the formatted result console.log(JSON.stringify(output, null, 2));
How This Works
Let's break down the logic step by step:
- Start with an empty object: We initialize
resultto build our final structure. - Loop through each entry: For every
[key, value]pair in the input array:- Recurse for nested arrays: If the value is an array where every item is another valid
[key, value]pair (length 2), we call the same function on that nested array to turn it into a sub-object. This handles any depth of nesting automatically. - Process primitive values: For non-array values, we add a quick check to convert string-formatted numbers (like
"1") to actual number types. This matches theid: 1in your desired output instead of keeping it as a string. If it's not a number string, we just use the value as-is (strings, booleans, etc.).
- Recurse for nested arrays: If the value is an array where every item is another valid
- Return the finished object: Once all entries are processed, we return the fully built object.
Sample Output
When you run this code with your input array, you'll get exactly the object you specified:
{ "seller": { "id": 1, "name": "test" }, "token": "aasfgsgd", "settings": { "general": false, "store": { "trusted": true, "socialMedia": { "fbConnected": true, "igConnected": false } } } }
This function is flexible enough to handle any variations of the nested array structure, as long as each level follows the [key, value] pattern you've shown.
内容的提问来源于stack exchange,提问作者user13266580

