I'd like to either find some existing middleware or some handy code to transform form fields with square brackets (i.e. 'contact[21][name]')into real arrays for ExpressJS 3.
Something along the lines of:
for(key in req.body){
if(key.isArrayField()) {
//add new array field to req.body and delete old string version from req.body
...
I'd like to to parse infinite depth of brackets. I'm still learning JS/Node so would love some direction.
Thanks
I'd like to either find some existing middleware or some handy code to transform form fields with square brackets (i.e. 'contact[21][name]')into real arrays for ExpressJS 3.
Something along the lines of:
for(key in req.body){
if(key.isArrayField()) {
//add new array field to req.body and delete old string version from req.body
...
I'd like to to parse infinite depth of brackets. I'm still learning JS/Node so would love some direction.
Thanks
Share Improve this question asked Sep 2, 2012 at 17:26 cyberwombatcyberwombat 40.3k41 gold badges184 silver badges267 bronze badges3 Answers
Reset to default 4Can you provide some clarification about what you're trying to achieve with this?
Depending on how you're getting the input from the web form in the first place you can easily parse JSON syntax into real objects (including arrays) using JSON.parse() (docs here) which is built into node.js
Using that method you can have an infinite level of nested values (hashes / objects, and arrays) but you'll need some client-side script to put the values there in the first place (jQuery for example).
If you give a fuller example, including the context of the form being submitted, I can probably give better direction...
In my experience you can simply do something like this...
Jade
input(type="text" name="foo[]" value="foo1")
input(type="text" name="foo[]" value="foo2")
JS
app.post('/test', function(req,res){
console.log(req.body)// { foo: [ 'foo1', 'foo2' ] }
console.log(req.body.foo)//["foo1","foo2"]
console.log(req.body.foo[0])//foo1
console.log(req.body.foo[1])//foo2
});
I don't know if this makes sense but this is how you treat them... at least on express 3.0+
I've sort of solved this by using https://github./marioizquierdo/jquery.serializeJSON - the issue is/was that if I just submit a POST form to express it doesn't handle brackets as an array so they have to be regexed manually. By parsing the form into JSON using the the plugin I can then submit it through ajax.