TransWikia.com

Pass object data as FormData

Stack Overflow Asked by Swarup Chavan on February 20, 2021

I’m receiving the data like this:

pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3", q2t: "", …}

Now I want to send this as FormData in my post call. I can’t make use of HTML form for this purpose, so in the http post call the data as to be as

systemId: "53183", pert-id: "176061", score: 0, q2c: "3", q2t: ""

I tried using FormData as

 var form_data = new FormData();
            for ( var key in this.dataObject['pert_submit'] ) {
                form_data.append(key, this.dataObject['pert_submit'][key]);
            }

How can I achieve it, pass FormData in the above specified format

(systemId: "53183", pert-id: "176061", score: 0, q2c: "3", q2t: "")

2 Answers

Been there with service guys that can't change; as mentioned in the comments, you have to create the string manually. Here's one way.

Note that to add to FormData, you need a key. Here I've used "pert_submit" from the example data; you'll need to work out what it should be with the service folk. You may also want to look at writing directly to the body of the request via fetch or XMLHttpRequest, which is a bit more challenging.

const data = {systemId: "53183", "pert-id": "176061", score: 0, q2c: "3", q2t: "" };
const getStringIfString = (val) => JSON.stringify(val);
const formattedOutput = Object.entries(data).reduce((agg, [key, val]) => `${agg}${agg.length ? ', ' : ''}${key}: ${getStringIfString(val)}`, "");
const formData = new FormData();
formData.append('pert_submit', formattedOutput);
console.log(formattedOutput);

One last thing to note: The value "3" is interpreted by JavaScript as the number 3 followed by a NUL character; that's why the log of the output here may seem a little odd.

Answered by Heretic Monkey on February 20, 2021

I like to use Object.entires when I need the key and value rather than Object.keys. You can use array destructuring in a .forEach loop to get both values in a clean way.

const data = {systemId: "53183", "pert-id": "176061", score: 0, q2c: "3", q2t: "" };
const formData = new FormData();

Object.entries(data).forEach(([key, value]) => formData.append(key, value))

console.log([...formData.entries()]);

Answered by iandev on February 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP