如何在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:
- Split the full query string into individual key-value pairs using
&as the separator - Iterate over each pair, split it into key and value, then use your
setValuefunction 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
setValuefunction: We kept your core logic intact since it efficiently handles creating nested objects on the fly usingreduce. - Handling multiple pairs:
Array.reducelets 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 number45, while non-numeric values stay as strings (if you don’t need this, just replaceprocessedValuewithvalue).
内容的提问来源于stack exchange,提问作者magnum888
相关产品推荐
相关产品推荐

