Using an HTML form with input fields will be problematic since there is no easy way to define the structure without parsing each field name to determine its place in the structure.
For instance, if you posted the following:
<form action="/post" method="post">
<input type="text" name="data[name]">
<input type="text" name="data[children][][child_name]">
<input type="text" name="data[children][][size]">
<input type="text" name="data[children][][child_name]">
<input type="text" name="data[children][][size]">
<input type="submit" value="Submit">
</form>
Formidable would interpret into this JSON structure:
[ [ 'data[name]', 'name' ],
[ 'data[children][][child_name]', [ 'cname1', 'cname2' ] ],
[ 'data[children][][size]', [ 'csize1', 'csize2' ] ] ]
To post deep structures this way, I would recommend using AJAX and posting a complete JSON object instead, which I have outlined below.
The following should allow you to copy all of the fields directly into req.body
. I elected to use the .mixin()
helper from the utile library.
var utile = require('utile')
var form = new formidable.IncomingForm()
, fields = {}
form
.on('field', function (field, value) {
fields[field] = value
})
.on('end', function () {
req.body = utile.mixin(req.body, fields)
})
Based on your JSON in the question itself, you could then access your values like this:
console.log(req.body.children[0].child_name)
If you are looking for a native way of merging the objects, see Combine or merge JSON on node.js without jQuery for a way to do this.
Hopefully this answers the question and helps you out!