Last active
January 12, 2022 10:53
-
-
Save pistou/f046a3fe483ae1308a68f14b91058082 to your computer and use it in GitHub Desktop.
URL Parameters transformation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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