Skip to content

Instantly share code, notes, and snippets.

@just806me
Last active May 7, 2020 13:42
Show Gist options
  • Save just806me/2d0c296a794b387b34e605f01b4f5ecf to your computer and use it in GitHub Desktop.
Save just806me/2d0c296a794b387b34e605f01b4f5ecf to your computer and use it in GitHub Desktop.
function getProperties(prefix, obj) {
if (obj === null || obj === undefined) {
return [];
}
if (obj instanceof Blob || obj instanceof File) {
return [{ name: prefix, value: obj }];
}
if (typeof obj !== 'object') {
return [{ name: prefix, value: obj.toString() }];
}
const properties = [];
Object.keys(obj).forEach(key => {
const value = obj[key], name = `${prefix}[${key}]`;
if (Array.isArray(value)) {
value.forEach(arrItem => properties.push(...getProperties(name + '[]', arrItem)));
}
else {
properties.push(...getProperties(name, value));
}
})
return properties;
}
function toFormData(prefix, obj) {
const formData = new FormData();
getProperties(prefix, obj).forEach(({ name, value }) => formData.append(name, value));
return formData;
}
const formData = toFormData('profile', data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment