Skip to content

Instantly share code, notes, and snippets.

@edvaldoszy
Created July 12, 2021 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edvaldoszy/a5bcd577ea67c7095064a43aa18173e3 to your computer and use it in GitHub Desktop.
Save edvaldoszy/a5bcd577ea67c7095064a43aa18173e3 to your computer and use it in GitHub Desktop.
function getPathWithKey(path, key) {
return typeof path === 'string' ? `${path}[${key}]` : key;
}
/**
* Esta função converte um objeto plano com chaves aninhadas para
* o formato esperado pelo URLSearchParams, que é utilizado nas requisições
* que exige o "Content-Type": "application/x-www-form-urlencoded".
*
* Um objeto com estrutura
* ```
* {
* name: 'John Doe',
* address: {
* line1: 'Street name'
* }
* }
* ```
*
* é convertido em
* ```
* [
* ['name', 'John Doe'],
* ['address[line1]', 'Street name']
* ]
* ```
*
* @param {null|string} path
* @param {object} payload
* @returns {string[][]}
*/
function nestedObjectToFlattenArray(path, payload) {
return Object.entries(payload)
.flatMap(([key, value]) => {
const pathWithKey = getPathWithKey(path, key);
if (toString.call(value) === '[object Object]') {
return nestedObjectToFlattenArray(pathWithKey, value);
}
return [[pathWithKey, value]];
});
}
const payload = {
name: 'John Doe',
address: {
line1: 'Street name',
line2: 'Number',
},
};
const flattenArray = nestedObjectToFlattenArray(null, payload);
const params new URLSearchParams(flattenArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment