0

I have this clever little piece of vanilla Javascript that converts url params into a hash:

"a=a&b=b".split("&").reduce((function(params, param) {
  var param_split = param.split("=").map(function(value) {
    return decodeURIComponent(value.replace("+", " "));
  });
  params[param_split[0]] = param_split[1];
  return params;
}), {});

Which outputs this hash:

{
  a: "a",
  b: "b"
}

But sometimes I get url params that are nested like this:

"a=a&b%5Bc%5D=bc&b%5Bd%5D=bd"

My script would output:

{
  a: "a",
  b[c]: "bc",
  b[d]: "bd"
}

What should I do in order to be able to output a nested hash like this?:

{
  a: "a",
  b: {
    c: "bc",
    d: "bd"
  }
}
JohnSmith1976
  • 536
  • 2
  • 12
  • 35
  • See https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path?noredirect=1&lq=1 for how to access nested elements from notation like this. Similar logic can be used to create them. – Barmar Feb 26 '21 at 22:20
  • Also see https://stackoverflow.com/questions/62684251/create-json-object-tree-from-looped-string-without-using-eval?noredirect=1&lq=1 – Barmar Feb 26 '21 at 22:20
  • FYI it's called "object" in JavaScript. "hash" is Perl. – Barmar Feb 26 '21 at 22:21
  • Here is an earlier answer of mine: https://stackoverflow.com/questions/1131630/the-param-inverse-function-in-javascript-jquery/38791705?r=SearchResults&s=1|27.5551#38791705 – Carsten Massmann Feb 26 '21 at 22:25

0 Answers0