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

如何在JavaScript中将指定格式的字符串解析为嵌套对象

解析URL查询字符串为嵌套对象

需求说明

输入查询字符串:

'user.name.firstName=Anatoliy&user.name.lastName=Klimov&user.vip=true'

需要解析为如下嵌套结构的对象(修正了原示例中的语法错误):

{
  "user": {
    "name": {
      "firstname": "Anatoliy",
      "lastname": "Klimov"
    },
    "vip": true
  }
}

实现方案(JavaScript)

以下是直接可用的解析函数,包含键名驼峰转小写、值类型转换(布尔/数字/字符串)、嵌套对象构建的逻辑:

function parseQueryStringToNestedObj(queryStr) {
  const result = {};
  const pairs = queryStr.split('&');
  
  pairs.forEach(pair => {
    const [keyPath, rawValue] = pair.split('=');
    if (!keyPath || rawValue === undefined) return;
    
    const decodedKeyPath = decodeURIComponent(keyPath);
    const decodedValue = decodeURIComponent(rawValue);
    
    // 处理值类型
    let value;
    if (decodedValue === 'true') {
      value = true;
    } else if (decodedValue === 'false') {
      value = false;
    } else if (!isNaN(decodedValue) && decodedValue.trim() !== '') {
      value = Number(decodedValue);
    } else {
      value = decodedValue;
    }
    
    // 驼峰键转全小写,分割路径
    const keys = decodedKeyPath.split('.').map(key => 
      key.replace(/([A-Z])/g, match => match.toLowerCase())
    );
    
    // 逐层构建嵌套对象
    let current = result;
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (i === keys.length - 1) {
        current[key] = value;
      } else {
        current[key] = current[key] || {};
        current = current[key];
      }
    }
  });
  
  return result;
}

// 测试示例
const inputStr = 'user.name.firstName=Anatoliy&user.name.lastName=Klimov&user.vip=true';
const outputObj = parseQueryStringToNestedObj(inputStr);
console.log(JSON.stringify(outputObj, null, 2));

关键逻辑说明

  • 键值对分割:用&拆分字符串,再用=拆分每个键值对,同时做URI解码兼容特殊字符
  • 值类型转换:自动识别布尔值(true/false)、数字,其他情况保留字符串
  • 驼峰转小写:通过正则表达式将firstName这类驼峰键转为firstname
  • 嵌套对象构建:通过循环逐层遍历键路径,不存在的对象自动创建,最终赋值到对应位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:18:34