Skip to content

Instantly share code, notes, and snippets.

@areichman
Last active July 5, 2023 22:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save areichman/c6485e19d3c3765751fc to your computer and use it in GitHub Desktop.
Save areichman/c6485e19d3c3765751fc to your computer and use it in GitHub Desktop.
Make the nested fields parsed by multiparty look like req.body from body-parser
// Make the nested fields parsed by multiparty look like req.body from body-parser
// e.g. 'metadata[foo]': ['1'] => {metadata: {foo: 1}}
// 'metadata[foo]': ['bar'] => {metadata: {foo: 'bar'}}
// 'metadata[foo][]': ['bar', 'bat'] => {metadata: {foo: ['bar', 'bat']}}
var qs = require('qs');
function reformatFields(fields) {
// convert numbers to real numbers instead of strings
function toNumber(i) {
return i !== '' && !isNaN(i) ? Number(i) : i;
}
// remove the extra array wrapper around the values
for (var f in fields) {
if (f === 'null') {
delete fields[f]; // ignore null fields like submit
} else {
if (f.match(/\[\]$/)) {
// if our key uses array syntax we can make qs.parse produce the intended result
// by removing the trailing [] on the key
var key = f.replace(/\[\]$/,'');
fields[key] = fields[f].map(function(i) { return toNumber(i) });
delete fields[f];
} else {
// for scalar values, just extract the single value
fields[f] = toNumber(fields[f][0]);
}
}
}
return qs.parse(fields);
};
// later in your app...
form.parse(req, function(err, fields, files) {
var _fields = reformatFields(fields);
console.log(_fields);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment