JavaScript:如何将含斜杠分割字符串的对象转为嵌套属性对象?
把路径字符串转为嵌套对象的实现方法
现有如下对象:
const obj = { name: 'root/branch/subbranch/leaf', value: 'my-value' }
需要基于name的路径字符串,生成如下嵌套结构的对象:
{ root: { branch: { subbranch: { leaf: 'my-value' } } } }
方法一:基础循环实现
这种方式逻辑直白,容易理解:
- 把
name按/分割成路径数组,得到['root', 'branch', 'subbranch', 'leaf'] - 初始化最终结果对象和一个临时变量,用来追踪当前层级的对象
- 遍历路径数组(除最后一个元素),逐层创建空对象并更新临时变量的指向
- 给最后一个路径节点赋值
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
相关产品推荐
相关产品推荐

