Skip to content

Instantly share code, notes, and snippets.

@TimurM
Created July 20, 2015 15:10
Show Gist options
  • Save TimurM/05b5c54292abfbbfe14a to your computer and use it in GitHub Desktop.
Save TimurM/05b5c54292abfbbfe14a to your computer and use it in GitHub Desktop.
queryMap = {
address: "3400 stratford",
full_name: {
first_name: 'Timur',
last_name: 'Meyster'
},
email: '[email protected]'
}
var turnMapToArray = function(queryMap) {
return Object.keys(queryMap).reduce(function(arrKeyVal, key) {
if(typeof queryMap[key] === 'object') {
return arrKeyVal.concat([[key, turnMapToArray(queryMap[key])]]);
} else {
return arrKeyVal.concat([[encodeURIComponent(key), encodeURIComponent(queryMap[key])]]);
}
}, [])
}
var joinArrayStrings = function(arrayStr) {
return arrayStr.reduce(function(joinedArray, arrayItem) {
if(typeof arrayItem[1] === 'string') {
return joinedArray.concat(arrayItem.join("="));
} else {
return joinedArray.concat(nestedMap(arrayItem));
}
}, [])
}
var nestedMap = function(arrayItem) {
var key = arrayItem[0];
return arrayItem[1].reduce(function(output, keyValue) {
var nestedKey = encodeURIComponent([key, keyValue[0]].join("[").concat("]"));
return output.concat([nestedKey, keyValue[1]].join("="));
}, []);
}
var convertToQueryStr = function(arrayKeyValueStr) {
return arrayKeyValueStr.join("&");
}
console.log(convertToQueryStr(joinArrayStrings(turnMapToArray(queryMap))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment