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

JavaScript:如何将含斜杠分割字符串的对象转为嵌套属性对象?

把路径字符串转为嵌套对象的实现方法

现有如下对象:

const obj = {
  name: 'root/branch/subbranch/leaf',
  value: 'my-value'
}

需要基于name的路径字符串,生成如下嵌套结构的对象:

{
  root: {
    branch: {
      subbranch: {
        leaf: 'my-value'
      }
    }
  }
}

方法一:基础循环实现

这种方式逻辑直白,容易理解:

  1. 把name按/分割成路径数组,得到['root', 'branch', 'subbranch', 'leaf']
  2. 初始化最终结果对象和一个临时变量,用来追踪当前层级的对象
  3. 遍历路径数组(除最后一个元素),逐层创建空对象并更新临时变量的指向
  4. 给最后一个路径节点赋值obj.value

代码示例:

const obj = {
  name: 'root/branch/subbranch/leaf',
  value: 'my-value'
};

const pathSegments = obj.name.split('/');
const nestedObj = {};
let currentLevel = nestedObj;

// 遍历到倒数第二个节点,构建层级
for (let i = 0; i < pathSegments.length - 1; i++) {
  const key = pathSegments[i];
  currentLevel[key] = {};
  currentLevel = currentLevel[key];
}
// 给最后一个节点赋值
currentLevel[pathSegments[pathSegments.length - 1]] = obj.value;

console.log(nestedObj);

方法二:使用Array.reduce简化实现

利用数组的reduce方法可以更简洁地完成逻辑,适合熟悉现代JavaScript语法的场景:

const obj = {
  name: 'root/branch/subbranch/leaf',
  value: 'my-value'
};

const nestedObj = {};
obj.name.split('/').reduce((current, key, index, arr) => {
  // 最后一个节点直接赋值
  if (index === arr.length - 1) {
    current[key] = obj.value;
  } else {
    // 非最后节点创建空对象,继续向下层级
    current[key] = {};
  }
  return current[key];
}, nestedObj);

console.log(nestedObj);

两种方法都能实现需求,循环方式更直观,reduce写法更简洁,可根据自己的习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:50:34