Serialize a javascript object to a query string for posting code example
Example: js deep serialize url array
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;
};