Created
August 10, 2017 15:45
-
-
Save phcorp/5803b2602ed43d43fa45847104521dcd to your computer and use it in GitHub Desktop.
Vanilla Javascript FormData to object
This file contains 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
/* | |
* Converts FormData to object. | |
* | |
* @param {FormData} data | |
* To convert. | |
* @return {string} | |
* FormData converted to object. | |
*/ | |
function formDataToObject(data) { | |
let value; | |
let keys; | |
let key; | |
let part; | |
let count; | |
let object = {}; | |
for (let pair of data.entries()) { | |
value = pair[1]; | |
keys = pair[0].split(/[\[\]]+/g); | |
key = keys.shift(); | |
part = object; | |
while (typeof key !== 'undefined') { | |
if (key === '') { | |
count = 0; | |
while (part.hasOwnProperty(count)) { | |
++count; | |
} | |
key = count; | |
} | |
part[key] = keys.length ? {} : value; | |
if (keys.length) { | |
part = part[key]; | |
} | |
key = keys.shift(); | |
} | |
} | |
return object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment