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

TypeScript如何将带点分隔key的对象数组转换为嵌套对象

TypeScript 点分隔key数组转嵌套对象实现

实现思路

  • 遍历输入数组的每一项,将点分隔的key字符串通过split('.')拆分为层级key数组
  • 逐层遍历层级key数组,过程中动态创建嵌套对象,遇到不存在的层级就初始化为空对象
  • 到达最后一级key时,将对应value赋值到该属性上

完整代码

// 定义输入数组的项类型
type KeyValueItem = {
  key: string;
  value: unknown;
};

// 转换函数
function convertToNestedObj(arr: KeyValueItem[]): Record<string, unknown> {
  const result: Record<string, unknown> = {};

  for (const item of arr) {
    // 拆分点分隔key为层级数组
    const keySegments = item.key.split('.');
    // 临时指针,指向当前处理的嵌套层级
    let currentLevel = result;

    for (let i = 0; i < keySegments.length; i++) {
      const currentKey = keySegments[i];
      // 处理最后一级key,直接赋值
      if (i === keySegments.length - 1) {
        // 如果需要统一转小写,这里可以写 currentKey.toLowerCase()
        currentLevel[currentKey] = item.value;
        break;
      }
      // 非最后一级,若不存在该属性则初始化为空对象
      if (!currentLevel[currentKey] || typeof currentLevel[currentKey] !== 'object') {
        currentLevel[currentKey] = {};
      }
      // 指针移动到下一层级
      currentLevel = currentLevel[currentKey] as Record<string, unknown>;
    }
  }

  return result;
}

测试用例

// 输入示例
const inputArr: KeyValueItem[] = [
  {"key": "key1", "value" : true },
  {"key": "key2.subKey1", "value" : true },
  {"key": "key2.subKey2", "value" : true },
];

const output = convertToNestedObj(inputArr);
console.log(output);

运行后输出的结构和要求完全匹配,如果你需要把subKey1转为全小写的subkey1,只需要在赋值的时候把currentKey替换为currentKey.toLowerCase()即可。

注意事项

如果数组中存在相同完整路径key的项,后出现的项的value会覆盖之前的赋值。
本实现默认保留key的原始大小写,如需统一大小写可在处理currentKey时调用toLowerCase()或toUpperCase()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:27:02