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

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 to undefined. If you want to handle this scenario, you can add a check like firstNestedKey ? currentValue[firstNestedKey] : null to default to a specific value.
  • Non-Object Values: Properties that aren't objects (like id and name in your example) are copied directly to the result object without any modifications.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:17:37