javascript object to params string
var queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
javascript object to params string
var queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
js deep serialize url array
/*
most answers in the thread do not serialize multi-level objects
this is probably bloated but works for nested arrays in objects
usage:
let querystring = flatten(myComplexJsObject)
*/
function flatten(object, prefix = ''){
let flatObject = Object.keys(object).reduce((carry, key) => {
const pre = prefix ? prefix + `[${key}]` : '';
if (Array.isArray(object[key])) {
carry = object[key].reduce((array, value, index) => {
array[(pre || key) + `[${index}]`] = value;
return array;
}, carry);
} else if (object[key] && typeof object[key] === 'object') {
Object.assign(carry, flatten(object[key], pre || key));
} else {
carry[pre || key] = object[key];
}
return carry;
}, {});
if(!flatObject || !flatObject.length) return '';
let querystring = flatObject.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
return querystring ? '?' + querystring : querystring;
};
javascript object to query string
queryBuilder = function(obj, prefix) {
var str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(
serialize({
foo: "hi there",
bar: {
blah: 123,
quux: [1, 2, 3]
}
})
);
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us