Skip to content

Instantly share code, notes, and snippets.

@camelaissani
Created July 1, 2017 10:45
Show Gist options
  • Save camelaissani/ffe163149f81437be0d3e54ccfc5544e to your computer and use it in GitHub Desktop.
Save camelaissani/ffe163149f81437be0d3e54ccfc5544e to your computer and use it in GitHub Desktop.
Javascript implementation of JQuery.param() $.param
function encodeURIObject = (obj, branch=[], results=[]) => {
if (obj instanceof Object) {
Object.keys(obj).forEach(key => {
const newBranch = new Array(...branch);
newBranch.push(key);
encodeURIObject(obj[key], newBranch, results);
});
return results.join('&');
}
if (branch.length>0){
results.push(`${encodeURIComponent(branch[0])}${branch.slice(1).map(el => encodeURIComponent(`[${el}]`)).join('')}=${encodeURIComponent(obj)}`);
} else if (typeof(obj) === 'string') {
return obj.split('').map((c,idx) => `${idx}=${encodeURIComponent(c)}`).join('&');
} else {
return '';
}
};
// Usage
encodeURIObject({
a: 'test',
b: 'éàâ',
c: [1,2,3,4],
d: {e:1,f:2}
});
// returns
// a=test&b=%C3%A9%C3%A0%C3%A2&c%5B0%5D=1&c%5B1%5D=2&c%5B2%5D=3&c%5B3%5D=4&d%5Be%5D=1&d%5Bf%5D=2
// after decodeURIComponent
// a=test&b=éàâ&c[0]=1&c[1]=2&c[2]=3&c[3]=4&d[e]=1&d[f]=2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment