2

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

3 Answers 3

4

Can 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...

Sign up to request clarification or add additional context in comments.

1 Comment

Sort of solved. I'll add my answer below though I'd still like to know of a piece of middleware that can parse POST forms from express and handle bracket notation.
3

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+

Comments

1

I've sort of solved this by using https://github.com/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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.