Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikhailsdv/32fe5e5bd42b05d9515fea2ac884c2f6 to your computer and use it in GitHub Desktop.
Save mikhailsdv/32fe5e5bd42b05d9515fea2ac884c2f6 to your computer and use it in GitHub Desktop.
Convert multidimensional JavaScript object to x-www-form-urlencoded request object.
const convert = function(arr, startPath = "") {
const getType = q => Object.prototype.toString.call(q);
function converter(list, path, result = {}) {
for (let key in list) {
let _path = `${path}[${key}]`;
let item = list[key];
let typeVal = getType(item);
if (("[object Array]" === typeVal) || ("[object Object]" === typeVal)) {
converter(item, _path, result);
} else {
result[_path] = item;
}
}
return result;
}
return converter(arr, startPath);
};
//let's say we have some complex object like this
let arr = [{"a":1,"b":[1,2,3]},[{"c":4,"d":5,"e":[6,{"f":7}]}],8];
console.log(convert(arr, "name")); //with name
/*
{
name[0][a]: 1
name[0][b][0]: 1
name[0][b][1]: 2
name[0][b][2]: 3
name[1][0][c]: 4
name[1][0][d]: 5
name[1][0][e][0]: 6
name[1][0][e][1][f]: 7
name[2]: 8
}
*/
console.log(convert(arr)); //without name
/*
{
[0][a]: 1
[0][b][0]: 1
[0][b][1]: 2
[0][b][2]: 3
[1][0][c]: 4
[1][0][d]: 5
[1][0][e][0]: 6
[1][0][e][1][f]: 7
[2]: 8
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment