1. function nestQueryString(queryString) {
  2. const params = {};
  3. const paramArray = queryString.startsWith('?') ? queryString.slice(1).split('&') : queryString.split('&');
  4. for (const param of paramArray) {
  5. const [key, value] = param.split('=');
  6. if (key) {
  7. const keyParts = key.split('.'); // Split by '.' to create nested structure
  8. let currentLevel = params;
  9. for (let i = 0; i < keyParts.length - 1; i++) {
  10. const part = keyParts[i];
  11. if (!currentLevel[part]) {
  12. currentLevel[part] = {}; // Create nested object if it doesn't exist
  13. }
  14. currentLevel = currentLevel[part];
  15. }
  16. currentLevel[keyParts[keyParts.length - 1]] = value ? value : true; // Assign value to the final level
  17. }
  18. }
  19. return params;
  20. }
  21. // Example usage:
  22. // const queryString = "param1=value1&param2.param3=value3&param2.param4=value4&param5=value5";
  23. // const nestedParams = nestQueryString(queryString);
  24. // console.log(nestedParams);

Add your comment