Last active
July 5, 2023 22:05
-
-
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
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
// 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