Created
July 12, 2021 20:46
-
-
Save edvaldoszy/a5bcd577ea67c7095064a43aa18173e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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