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

如何在JavaScript中将嵌套键值对字符串转换为单个对象?

JavaScript: Convert Nested Query String to a Nested Object

Great question! You’re already off to a fantastic start with your setValue function—it’s perfect for handling single key-value pairs with nested paths. Let’s build on that to handle the full query string with multiple pairs.

Here’s how to expand your solution:

Your existing setValue logic is solid—it creates nested objects as needed and assigns the value to the final key. We just need to:

  1. Split the full query string into individual key-value pairs using & as the separator
  2. Iterate over each pair, split it into key and value, then use your setValue function to build out the final nested object

We can even add a small touch to automatically convert numeric values to number types (matching your desired output), though you can remove that part if you want all values to stay strings.

Full Working Code

function queryStringToNestedObj(queryString) {
  // Reuse your excellent setValue function with optional numeric conversion
  function setValue(object, path, value) {
    const way = path.split('.');
    const last = way.pop();
    // Convert value to number if it's a valid numeric string
    const processedValue = isNaN(Number(value)) ? value : Number(value);
    way.reduce((o, k) => o[k] = o[k] || {}, object)[last] = processedValue;
    return object;
  }

  // Split the query string into individual key-value pairs
  const keyValuePairs = queryString.split('&');
  
  // Build the nested object by processing each pair
  return keyValuePairs.reduce((finalObj, pair) => {
    const [key, value] = pair.split('=');
    return setValue(finalObj, key, value);
  }, {});
}

// Test with your sample input
const inputString = "foo.call=45&doo.foo=20&foo.in=5";
const resultObj = queryStringToNestedObj(inputString);
console.log(resultObj);
// Output: { foo: { call: 45, in: 5 }, doo: { foo: 20 } }

// It also works for single key-value pairs like your original test case
const singlePair = "foo.call=45";
console.log(queryStringToNestedObj(singlePair));
// Output: { foo: { call: 45 } }

Key Details:

  • Reusing your setValue function: We kept your core logic intact since it efficiently handles creating nested objects on the fly using reduce.
  • Handling multiple pairs: Array.reduce lets us start with an empty object and add each key-value pair one by one.
  • Numeric conversion: The isNaN(Number(value)) check ensures that strings like "45" become the number 45, while non-numeric values stay as strings (if you don’t need this, just replace processedValue with value).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:40:26