Henri
Henri

Reputation: 1741

How to get structured object using POST endpoint in SvelteKit?

when I'm using the POST endpoint from Sveltekit, I get a "flat" object as output. How can I get a "structured" Object instead ?

Let's assume the following code:

index.svelte

<div class="container">
  <form method="post">
    <label for="firstname">Firstname</label>
    <input type="text" name="firstname" />

    <label for="lastname">Lastname</label>
    <input type="text" name="lastname" />

    <label for="dog">Dog 1</label>
    <input type="text" name="dog" />

    <label for="dog">Dog 2</label>
    <input type="text" name="dog" />

    <!-- ... -->

    <button>Save</button>
  </form>
</div>

index.js

export async function post({request}){
    const data = Object.fromEntries(await request.formData());
    console.log(data);

    return{}
}

Ouput (what I'm calling "flat" object)

{ firstname: 'foo', lastname: 'bar', dog: 'teckel', dog: 'labrador' }

Instead of that output, how should I proceed to get the following one in my index.js

Expected output:

{
  firstname: 'foo',
  lastname: 'bar',
  dogs: [ { dog: 'teckel' }, { dog: 'labrador' } ]
}

Upvotes: 1

Views: 1430

Answers (1)

brunnerh
brunnerh

Reputation: 184607

There are libraries that can perform a transform like this more or less automated. Some use conventions in the field names to parse the data into arrays and nested structures, others additionally use schemas to do type conversions or validation. E.g. to achieve an array of objects like this, one might set the names like this:

<label for="dog">Dog 1</label>
<input type="text" name="dogs[][dog]" />

<label for="dog">Dog 2</label>
<input type="text" name="dogs[][dog]" />

The [] Indicates that the field is part of an array, [dog] indicates that a property called dog is set on the element (.dog would also be reasonable).

So instead of calling Object.fromEntries you have to either parse the data yourself or find a library that does it for you. (Note that StackOverflow is not a place for library recommendations.)


Personally, I would avoid the synchronous form post and send JSON asynchronously instead, that way you can send in a fixed structure and receive that exact structure. Of course this requires binding/reading the form values yourself and the form will not work as intended if the JS failed to load.

Upvotes: 2

Related Questions