Handling input arrays in Express forms?
For bodyParser.urlencoded
, if you set the extended
option to true
, attribute names of the format property[nestedProperty]
will be interpreted by the bodyParser
middleware as:
{ property: nestedPropert: $value }
Just be sure to initialize the middleware like so:
app.use(bodyParser.urlencoded({ extended: true });
Afterwards, change the above form declaration to have the message property be an object, instead of a string value, like so:
form(action='', method='POST') - for (var i = 0; i < messages_ids.length; i++) - var message_id = messages_ids[i] //- so we're treating each index like a property of `message` input(type='text', name='messages[#{i}][message]') input(type='text', name='messages[{#{i}}][author]') input(type='hidden', name='messages[#{i}][id]', value='#{message_id}') input(type='submit', value='Send')
And then, on the server side, request.body.messages
would be an object, that looks like:
{ "messages": { "1": { "message": $message1, "author": $author1, "id": $id1 }, "2": { "message": $message2, "author": $author2, "id": $id2 } /* , ... */ }}
And then, you can easily convert request.body.messages
into an array:
var messages = Array.prototype.slice.call(request.body.messages);
And now, you should be able to access each elements like so (note: I prefer a functional style, but I'll keep it consistent with yours):
for (var i = 0; i < messages.length; i++) { console.log({ 'ObjectId' + messages[i].id, 'Message' + messages[i].message, 'Author' + messages[i].author });}
P.S.: if you're wondering of a functional style, then here it is:
messages.forEach(function (message) { console.log( 'ObjectId' + message.id, 'Message' + message.message, 'Author' + messages.author );});
Edit: special thanks to @eye_mew for pointing out that we need to set extended
to true
.