i have a dynamic form and i save all values in one useState
that name is formFields
and output like this:
{
title: "aaa",
description: "bbb",
second_description: "ccc",
step_number: 1,
image: null,
},
{
title: "zzz",
description: "xxx",
second_description: "eee",
step_number: 2,
image: null,
}
]
i sholud save this array of objects and send as POST request like this:
{
steps: [
{
title: "aaa",
description: "bbb",
second_description: "ccc",
step_number: 1,
image: null,
},
{
title: "zzz",
description: "xxx",
second_description: "eee",
step_number: 2,
image: null,
}
]
}
but with this code i can't append this objects inside steps[]
formFields.forEach((item) => {
formData.append("steps[]", item);
});
and show me in console like this:
steps: Array [ "[object Object]", "[object Object]" ]
objects save like string
in steps
! , but i want to save object
how i can do that?
CodePudding user response:
When you use the below code, it is not saved in the way you want
formFields.forEach((item) => {
formData.append("steps[]", item);
});
because steps
is an array, you need to assign the number of each array to it:
const name = "steps";
formFields.forEach((item,i) => {
formData.append((name '[' i ']' ["[title]"]), item["title"]);
formData.append((name '[' i ']' ["[description]"]), item["description"]);
formData.append((name '[' i ']' ["[second_description]"]), item["second_description"]);
formData.append((name '[' i ']' ["[step_number]"]), item["step_number"]);
});
CodePudding user response:
does this answer your question?
let formFields = [{
title: "aaa",
description: "bbb",
second_description: "ccc",
step_number: 1,
image: null,
},
{
title: "zzz",
description: "xxx",
second_description: "eee",
step_number: 2,
image: null,
}]
;
let formData = {};
formData.steps = [];
formFields.forEach((item) => {
formData.steps.push(item);
});
JSON.stringify(formData);
//output
'{"steps":[{"title":"aaa","description":"bbb","second_description":"ccc","step_number":1,"image":null},{"title":"zzz","description":"xxx","second_description":"eee","step_number":2,"image":null}]}'