Reputation: 165
In my nextjs form, I have inputs with names containing square brackets like
store[name]
store[homePage]
store[domain]
and I am using a server action to handle this form submission. but the received form data is a map like, i.e. to get the store name I write
formData.get('store[name]')
and so on.
how to get the submitted data as an object like
const store = formData.get('store');
this store is expected to be an object with the properties {name, homePage, domain}
like body parser in express js
searched for a solution but with no luck
Upvotes: 2
Views: 490
Reputation: 165
I could use lodash
to achieve this.
import _ from "lodash";
export default function parseFormData(formData) {
const object = {};
for (const [key, value] of formData.entries()) {
_.set(object, key, value);
}
return object;
}
const formData = new FormData();
formData.append("store[name]", "Some Name");
formData.append("store.homePage", "https://example.com");
formData.append("store.domain[0]", "example.com");
formData.append("address[city]", "New York");
formData.append("address[state]", "NY");
formData.append("categories[0]", "category1");
formData.append("categories[1]", "category2");
formData.append("nested[obj][prop1]", "value1");
formData.append("nested[obj][prop2]", "value2");
formData.append("simpleName", "Simple Value");
formData.append("complex[0][p][a][0]", "pppp");
formData.append("complex[0][p][b]", "dddd");
formData.append("complex[1][p][a][0]", "aaa");
formData.append("complex[1][p][b]", "bbb");
const dataObject = parseFormData(formData);
console.log(dataObject);
console.log(dataObject.complex);
output:
{
store: {
name: 'Some Name',
homePage: 'https://example.com',
domain: [ 'example.com' ]
},
address: { city: 'New York', state: 'NY' },
categories: [ 'category1', 'category2' ],
nested: { obj: { prop1: 'value1', prop2: 'value2' } },
simpleName: 'Simple Value',
complex: [ { p: [Object] }, { p: [Object] } ]
}
[ { p: { a: [Array], b: 'dddd' } }, { p: { a: [Array], b: 'bbb' } } ]
Upvotes: 2