1
\$\begingroup\$
let formData = new FormData();
 formData.append('File', document.file);
 formData.append('DocumentType', document.documentType);
 product = {
 ...values,
 productType: productT,
 };
 for (var key in product) {
 if (key != 'createdDate' && key != 'expirationDate') {
 formData.append(key, product[key]);
 } else {
 formData.append(key, new Date(product[key]).toUTCString());
 }
 }
 await createproduct(formData);

I need to send file and other data about product in one request so I added all the stuffs in FormData, and I have issues only with Dates, I must convert it to date because somehow it get confused if I don't convert it.

Can I somehow refactor this code to do this part about dates more elegant, if condition in for loop somehow smells bad..

P.S EDIT:

for (var key in product) {
 const transform = DateTransformer[key];
 formData.append(key, transform ? transform[product[key]] : product[key]);
}
asked Nov 15, 2019 at 20:37
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Transformation rules

Especially useful if there are many fields and each needs a unique rule.

const dateToUTCString = d => new Date(d).toUTCString();
const DataTransformer = {
 createdDate: dateToUTCString,
 expirationDate: dateToUTCString,
};
// [...]
for (const [key, calue] of Object.entries(product)) {
 const transform = DataTransformer[key];
 formData.append(key, transform ? transform(value) : value);
}
answered Nov 16, 2019 at 11:43
\$\endgroup\$
2
  • \$\begingroup\$ I don't understand how this works.. \$\endgroup\$ Commented Nov 18, 2019 at 7:59
  • \$\begingroup\$ The code is a standard JavaScript so I'm not sure what to clarify. \$\endgroup\$ Commented Nov 18, 2019 at 8:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.