Skip to content

Instantly share code, notes, and snippets.

@pistou
Last active January 12, 2022 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pistou/f046a3fe483ae1308a68f14b91058082 to your computer and use it in GitHub Desktop.
Save pistou/f046a3fe483ae1308a68f14b91058082 to your computer and use it in GitHub Desktop.
URL Parameters transformation
const objectToString = (o) => {
return Object.keys(o)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(o[k])}`)
.join('&');
};
const obj = {foo: "bar", abc: "xyz", name: "John Doe"};
const str = objectToString(obj);
console.log(str); // foo=bar&abc=xyz&name=John%20Doe
// ----
const stringToObject = (s) => {
return s
.split('&')
.map((o) =>
o.split('=').reduce((k, v) => ({
[decodeURIComponent(k)]: decodeURIComponent(v),
}))
)
.reduce((a, b) => ({ ...a, ...b }));
};
const obj2 = stringToObject(str);
console.log(obj2); // {foo: "bar", abc: "xyz", name: "John Doe"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment