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

JavaScript如何将点分隔属性路径字符串/数组展开为嵌套对象

JS实现属性路径转嵌套对象

针对点分隔的路径字符串(例如'users.data.object.email')、路径段数组(例如['users', 'data', 'object', 'email'])两类输入,要生成对应层级的嵌套对象,实现逻辑非常直接:

  • 先做输入归一化:字符串就按.拆分成数组,数组直接复用,顺手过滤掉空值,避免连续点、首尾点产生无效路径段
  • 从根空对象开始逐层遍历路径段,每一层如果不存在当前key就初始化空对象,之后把访问指针移到新建的子对象上,遍历完所有段就得到目标结构

完整实现代码:

function pathToNestedObject(path) {
  // 统一转换为路径段数组
  const pathSegments = Array.isArray(path) 
    ? [...path] 
    : path.split('.').filter(Boolean);

  const nestedObj = {};
  let currentLevel = nestedObj;

  for (const key of pathSegments) {
    // 当前层级无对应属性则初始化空对象
    if (typeof currentLevel[key] !== 'object') {
      currentLevel[key] = {};
    }
    // 指针移动到下一层级
    currentLevel = currentLevel[key];
  }

  return nestedObj;
}

使用示例:

// 传入字符串路径
const obj1 = pathToNestedObject('users.data.object.email');
// 传入数组路径
const obj2 = pathToNestedObject(['users', 'data', 'object', 'email']);

两个调用返回的结构完全一致,符合预期:

{
  users: {
    data: {
      object: {
        email: {}
      }
    }
  }
}

如果需要给最后一级属性赋具体值,只要在遍历到最后一个路径段时,把初始化空对象的逻辑改成赋值目标值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 16:21:21