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

如何在TypeScript中将二维JSON对象转换为一维JSON对象

如何在TypeScript中将嵌套JSON对象扁平化为一维对象?

你需要把嵌套结构的JSON对象,通过递归遍历将嵌套键用点连接,转化为一维键值对结构。以下是具体实现方案:

实现思路

  1. 递归遍历输入对象的每个属性
  2. 若属性值是非数组、非null的对象,则递归处理该子对象,将父键与子键用.拼接作为新键
  3. 若属性值是基本类型(字符串、数字等),则直接将拼接后的键和对应值存入结果对象

TypeScript 代码实现

先定义扁平化对象的类型,再实现递归扁平化函数:

// 定义扁平化后的对象类型
type FlattenedObject = { [key: string]: string | number | boolean };

/**
 * 扁平化嵌套对象
 * @param obj 待扁平化的嵌套对象
 * @param parentKey 父级键(递归时自动传递)
 * @param result 结果对象(递归时自动传递)
 * @returns 扁平化后的一维对象
 */
function flattenObject(
  obj: Record<string, any>,
  parentKey: string = '',
  result: FlattenedObject = {}
): FlattenedObject {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const currentKey = parentKey ? `${parentKey}.${key}` : key;
      const value = obj[key];

      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        flattenObject(value, currentKey, result);
      } else {
        result[currentKey] = value;
      }
    }
  }
  return result;
}

测试示例

用你提供的输入对象测试:

// 输入的嵌套JSON对象
const nestedObj = {
  summary: {
    name: 'test1',
    age: '12',
    gender: 'M'
  },
  address: {
    line1: 'Line1 address test',
    line2: 'Line 2 Adress test'
  }
};

// 调用扁平化函数
const flattenedObj = flattenObject(nestedObj);

console.log(flattenedObj);

输出结果:

{
  "summary.name": "test1",
  "summary.age": "12",
  "summary.gender": "M",
  "address.line1": "Line1 address test",
  "address.line2": "Line 2 Adress test"
}

扩展说明

  • 如果需要处理数组类型的属性值,可以在判断逻辑中添加数组分支,比如将索引作为键的一部分(如list.0.item)
  • 函数用hasOwnProperty确保只处理对象自身属性,避免遍历原型链上的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:40:31