Solution 1 :

If you would like to have a collection/array, you could generate the form as follows:

<input type="text" name="positions[]" />
<input type="text" name="positions[]" />
<input type="text" name="positions[]" />
<input type="text" name="positions[]" />

In node js/server side you could expect your data in req.body.positions like this

[
  1,
  2,
  3,
  4
]

If the suffix or number at the end of the name is something you would like to keep, you could consider transforming your data eg

var transformedPositions = req.body.positions.map(function(positionValue,index){
   var newKeyName = "position"+(index+1);
   return {newKeyName:positionValue}
})

which would then give you this in transformedPositions

[
 {position1: '1'},
 {position2: '2'},
 {position3: '3'},
 {position4: '4'},
]

Problem :

I have a form data where I used the loop to generate the input type text fields.

So with the help of loop, when I open the form data through inspect element, i got something like this:

< input type="text" name="position1" />
< input type="text" name="position2" />
< input type="text" name="position3" />
< input type="text" name="position4" />

when I submit the form, On Node.js when I fetch the request through request.body i got something like this:

{
      position1: '1',
      position2: '2',
      position3: '3',
      position4: '4'
}

what I am looking is like

[
 {position1: '1'},
 {position2: '2'},
 {position3: '3'},
 {position4: '4'},
]

so that I used the map function to update the value one by one on mongodb or use the bulkwrite function to update all at once.

I tried to put [] before the value on name=””. Like this name=”[]position1″ but not getting success.

Is there any one who can guide me on this.

Comments

Comment posted by Harmandeep Singh Kalsi

You can do something like . var arr = [{ position1: ‘1’, position2: ‘2’, position3: ‘3’, position4: ‘4’ }]

Comment posted by Taplar

Object.keys(theRequestBody)

Comment posted by Ankit

@HarmandeepSinghKalsi can you elaborate it please. In your answer I am not getting what you are trying to guide me. I know array of objects handling. My question is if I send the value under loop in form data then on server side I got the single objects with multiple values. How to segregate this from single object to multiple objects under an array

Comment posted by Ankit

@Taplar it return the array with multiple values

Comment posted by Taplar

console.log(Object.keys({position1: '1',position2: '2',position3: '3',position4: '4'}))

By

Leave a Reply

Your email address will not be published. Required fields are marked *