javascriptreactjsformsnext.js

Structure HTML form to create a array of objects using form data


I have a HTML form that's using the react form action using form data.

When extracting formData from my method it shows likes:

enter image description here

What I'm trying to achieve or my expectation is that I would get an array of objects:


  "completeSuccessIndicators": [
    {
    "si": 1,
    "actual_accomplishment": "this the acutal accomplishmentsasdfasdfas",
    "ql_qn": 1,
    "timeliness": 3,
    "average": 3,
    "remarks": "asdfasdf"
    },
    {
    "si": 2,
    "actual_accomplishment": "this the acutal 2222123123s",
    "ql_qn": 1,
    "timeliness": 3,
    "average": 3,
    "remarks": "another remarks"
    }
  ]

Is there away for it to be automatic like PHP or Ruby on Rails? or is there a package that I could use? Right now I'm thinking of creating a logic to parse form data.

PS: I'm using Next.js for my React project.


Solution

    1. Install Radash package with npm i radash. It's a more modern and lightweight replacement for Lodash.

    2. Simply do:

    import { construct } from 'radash'
    
    const formDataObject = Object.fromEntries(formData.entries())
    const finalObject = construct(formDataObject)
    

    The finalObject is what you need.

    Alternatively, you can try using Formik or different libraries for building forms in React.