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;
};
Also in JavaScript:
- how to check if a javascript object is empty
- Syntax Error: Thread Loader (Worker 0) .eslintrc.js: Environment key "es2021" is unknown at Array.forEach (<anonymous>)
- Angular comment
- w3schools ajax
- react native keyboard event listener
- node.js wikipedia api call
- add delay for keypress event in extjs
- how to generate random text in vue js
- electron specify minimum size
- mongoose bulk update
- javascript on click radio button get value
- how to set background colour i js inline stylel
- export component in
- react onclick parameter
- javascript image xss
- dustjs compilator
- disable autocomplete in react fields
- javascript get 24 hour time
- remove space from string javascript
- how to send message to specific client using ws node js
- node code comment process real time
- javascript ascending and descending
- check if value is NaN
- datatables change width of columns