Forms of array elements in node and express

Despite all my efforts, I was stuck in getting array keys for form elements introduced in NodeJS, Express, and handlebars.

The elements of my form are as follows:

{{#each block}}
<input type='text' name='block_payout[{{id}}]' />
{{/each}

This results in the following markup in the browser:

<input type='text' name='block_payout[14]' />
<input type='text' name='block_payout[15]' />
<input type='text' name='block_payout[16]' />

In PHP, this will lead to the array as an element of the $ _POST array:

$_POST [
  block_payout [
    14 => value1
    15 => value2
    16 => value3
  ]
]

However, the req.body property in Node / Express removes these keys and creates an indexed array:

req.body [
  block_payout [
    0 => value1
    1 => value2
    2 => value3
  ]
]

Since I want to use the key to bind the presented values ​​to something else, for me this is a big problem. Does anyone know how I can get the provided form data with the correct keys?

+4
source share
1 answer

, ( 0), , , , . , :

  • , . :

    <input type='hidden' name='block_payout[null]' />
    <input type='text' name='block_payout[14]' />
    ...
    

    :

    { block_payout: { '14': 'test1', '15': 'test2', '16': 'test3', null: '' } }
    
  • , . :

    <input type='text' name='block_payout[i14]' />
    ...
    

    :

    { block_payout: { i14: 'test1', i15: 'test2', i16: 'test3' } }
    
+3

Source: https://habr.com/ru/post/1530241/


All Articles