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

如何将点分隔的字符串转换为嵌套JavaScript对象或JSON结构

点分隔字符串转嵌套JavaScript对象实现方法

实现思路

将点分隔的字符串按.拆分出层级键组,从根对象开始逐层构建嵌套结构,最后一级键对应的取值设置为空字符串即可。

代码实现

原始字符串:

let str = "modules.mas.mas-helper-provider.assets.locales";

转换函数:

function buildNestedObject(dotStr, leafValue = '') {
  const keyList = dotStr.split('.');
  const root = {};
  let currentLevel = root;

  for (let index = 0; index < keyList.length; index++) {
    const currentKey = keyList[index];
    // 遍历到最后一个键时赋值为目标叶子值
    if (index === keyList.length - 1) {
      currentLevel[currentKey] = leafValue;
      break;
    }
    // 对应键不存在则初始化空对象
    if (!currentLevel[currentKey]) {
      currentLevel[currentKey] = {};
    }
    // 层级指针下移
    currentLevel = currentLevel[currentKey];
  }
  return root;
}

// 调用示例
const targetObj = buildNestedObject(str);
// 格式化输出JSON
console.log(JSON.stringify(targetObj, null, 2));

输出结果

执行后输出的JSON与需求完全一致:

{
  "modules": {
    "mas": {
      "mas-helper-provider": {
        "assets": {
          "locales": ""
        }
      }
    }
  }
}

你也可以通过修改leafValue参数自定义最后一层的取值,满足不同场景的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:45:07