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

如何将字符串二维数组转换为各级字符串为键的嵌套对象

数组转嵌套对象实现方案

实现思路

  • 先初始化一个空对象作为最终输出结果
  • 遍历原始数组中的每一组路径数组
  • 对每组路径,使用临时指针从根对象开始逐层向下遍历节点
  • 每个节点名统一格式化:全转小写,空格替换为下划线,匹配示例输出要求
  • 若当前层级不存在该节点属性,直接初始化为空对象
  • 指针移动到当前节点对象,继续处理下一级节点,直到当前路径遍历完成

代码实现

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
]

const result = {}

array.forEach(path => {
  // 临时指针,记录当前遍历到的对象层级
  let current = result
  path.forEach(key => {
    // 格式化key:全小写+空格替换为下划线
    const formattedKey = key.toLowerCase().replaceAll(' ', '_')
    // 不存在对应属性则初始化空对象
    if (!current[formattedKey]) {
      current[formattedKey] = {}
    }
    // 指针移动到下一层
    current = current[formattedKey]
  })
})

如果需要兼容不支持replaceAll的低版本JS环境,可以把格式化key的逻辑替换为:

const formattedKey = key.toLowerCase().replace(/\s+/g, '_')

执行完成后result就是你需要的目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:15:02