如何将JavaScript对象转换为自定义格式的数组
Got it, let's work through this problem step by step. You need to convert a nested JavaScript object into a flat array where each field (including nested ones using dot notation) is represented by four consecutive entries: the field path, its value, the field path with a _type suffix, and the data type. Here's how to do it:
Step 1: Define a Helper Function to Get Data Types
First, we need a reliable way to determine the type of each value—since typeof returns "object" for arrays, we'll add a check for that:
function getDataType(value) { if (Array.isArray(value)) { return 'array'; } return typeof value; }
Step 2: Recursive Function to Flatten the Object
We'll use recursion to handle nested objects, building the dot-separated path as we go. For basic types (string, number, boolean), we add the actual value; for arrays and objects, we use the type as the value (matching your example format) and recursively process nested objects (but leave arrays as top-level entries without expanding their elements):
function flattenObjectToArray(obj, currentPath = '', result = []) { // Iterate over each key in the current object for (const key of Object.keys(obj)) { // Build the full dot-separated path for the field const fullFieldPath = currentPath ? `${currentPath}.${key}` : key; const value = obj[key]; const dataType = getDataType(value); // Handle basic data types if (['string', 'number', 'boolean'].includes(dataType)) { result.push( fullFieldPath, String(value), // Convert value to string to match example format `${fullFieldPath}_type`, dataType ); } // Handle arrays and objects else if (dataType === 'array' || dataType === 'object') { result.push( fullFieldPath, dataType, // Use type as value for complex types `${fullFieldPath}_type`, dataType ); // Recursively process nested objects (skip arrays to avoid expanding elements) if (dataType === 'object' && value !== null) { flattenObjectToArray(value, fullFieldPath, result); } } } return result; }
Step 3: Test with Your Object
Let's apply this function to your sample object:
// Your original object const userData = { username: 'hamet', weight: 75, active: false, data: { interestedIn: ['internet', 'ping pong'], anotherArr: [{ data: [1, 2, 3] }], anotherObj: { favoriteColor: 'blue', isStudent: true } } }; // Generate the flattened array const flattenedArr = flattenObjectToArray(userData); console.log(flattenedArr);
Output
The resulting array will look like this:
[ "username", "hamet", "username_type", "string", "weight", "75", "weight_type", "number", "active", "false", "active_type", "boolean", "data.interestedIn", "array", "data.interestedIn_type", "array", "data.anotherArr", "array", "data.anotherArr_type", "array", "data.anotherObj", "object", "data.anotherObj_type", "object", "data.anotherObj.favoriteColor", "blue", "data.anotherObj.favoriteColor_type", "string", "data.anotherObj.isStudent", "true", "data.anotherObj.isStudent_type", "boolean" ]
Key Notes
- Nested Paths: Dot notation is used for all nested fields (e.g.,
data.anotherObj.favoriteColor). - Basic Types: Actual values are converted to strings to match your example's format (e.g.,
falsebecomes"false"). - Complex Types: Arrays and objects are recorded with their type as the value, and nested objects are processed recursively (arrays are not expanded to keep the array focused on top-level fields).
内容的提问来源于stack exchange,提问作者Hamet Gholizadeh

