TypeScript中如何将含嵌套对象的对象映射为单个对象(取首元素)
Solution for Object Transformation: Extract First Value from Nested Objects
Hey there, let's work through this object mapping problem. The goal is clear: whenever we encounter a nested object with multiple properties, we replace that nested object with the value of its first property. Here's a clean, reusable way to pull this off in JavaScript:
Step-by-Step Implementation
First, we'll create a function that iterates over the original object, checks for nested objects, and extracts the first value where needed.
// Your original object const obj = { id:"111", name:"sven", nicknames:{ name1:"svini", name2:"sivi" }, cars: { car1 : "BMW", car2 : "mercedies" } }; // Transformation function function flattenNestedObjects(original) { const result = {}; // Loop through each key in the original object for (const key of Object.keys(original)) { const currentValue = original[key]; // Check if the value is a non-null, non-array object if (typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue)) { // Grab the first key of the nested object and its corresponding value const firstNestedKey = Object.keys(currentValue)[0]; result[key] = currentValue[firstNestedKey]; } else { // If it's not a nested object, keep the value as-is result[key] = currentValue; } } return result; } // Run the transformation const convertedObject = flattenNestedObjects(obj); console.log(convertedObject); // Output: { id: '111', name: 'sven', nicknames: 'svini', cars: 'BMW' }
Key Details to Keep in Mind
- Key Order Reliability: In modern JavaScript (ES6+), object keys preserve their insertion order for non-integer keys. So
Object.keys(value)[0]will consistently grab the first property you defined in the nested object, which aligns perfectly with your requirement. - Empty Nested Objects: If a nested object is empty (e.g.,
nicknames: {}), this code will set the value toundefined. If you want to handle this scenario, you can add a check likefirstNestedKey ? currentValue[firstNestedKey] : nullto default to a specific value. - Non-Object Values: Properties that aren't objects (like
idandnamein your example) are copied directly to the result object without any modifications.
内容的提问来源于stack exchange,提问作者user10171513
相关产品推荐
相关产品推荐

