Created
May 17, 2012 22:42
-
-
Save luk-/2722097 to your computer and use it in GitHub Desktop.
php's http_build_query() in javascript
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
var build_query = function (obj, num_prefix, temp_key) { | |
var output_string = [] | |
Object.keys(obj).forEach(function (val) { | |
var key = val; | |
num_prefix && !isNaN(key) ? key = num_prefix + key : '' | |
var key = encodeURIComponent(key.replace(/[!'()*]/g, escape)); | |
temp_key ? key = temp_key + '[' + key + ']' : '' | |
if (typeof obj[val] === 'object') { | |
var query = build_query(obj[val], null, key) | |
output_string.push(query) | |
} | |
else { | |
var value = encodeURIComponent(obj[val].replace(/[!'()*]/g, escape)); | |
output_string.push(key + '=' + value) | |
} | |
}) | |
return output_string.join('&') | |
} |
Author
luk-
commented
May 17, 2012
This does not work with arrays,
build_query({
data: '1',
terms: [
123,
234,
]
});
Must give
?data=1&terms[0]=123&terms[1]=234
tnx helper function
nodejs8.4
const querystring = require('querystring');
/** @see https://gist.github.com/luk-/2722097 */
exports.buildQuery = function (obj, numPrefix, tempKey) {
let output_string = [];
Object.keys(obj).forEach(function (val) {
let key = val;
numPrefix && !isNaN(key) ? key = numPrefix + key : '';
key = encodeURIComponent(String(key).replace(/[!'()*]/g, querystring.escape));
tempKey ? key = tempKey + '[' + key + ']' : '';
if (typeof obj[val] === 'object') {
let query = exports.buildQuery(obj[val], null, key);
output_string.push(query)
}
else {
let value = encodeURIComponent(String(obj[val]).replace(/[!'()*]/g, querystring.escape));
output_string.push(key + '=' + value)
}
});
return output_string.join('&')
};
for just key value pairs.
function http_build_query(jsonObj) {
const keys = Object.keys(jsonObj);
const values = keys.map(key => jsonObj[key]);
return keys
.map((key, index) => {
return `${key}=${values[index]}`;
})
.join("&");
};
console.log(http_build_query({username: 'asd', password: '1234'}));
Does
function http_build_query (obj, num_prefix , temp_key) {
let output_string = [];
Object.keys(obj).forEach(function (val) {
let key = val;
num_prefix && !isNaN(key) ? key = num_prefix + key : '';
key = encodeURIComponent(String(key).replace(/[!'()*]/g, querystring.escape));
temp_key ? key = temp_key + '[' + key + ']' : '';
if (typeof obj[val] === 'object') {
let query = http_build_query(obj[val], null, key);
output_string.push(query);
}
else {
let value = encodeURIComponent(String(obj[val]).replace(/[!'()*]/g, querystring.escape));
output_string.push(key + '=' + value)
}
});
return output_string.join('&')
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment