'How to convert a iterator (FormData) to an object
Given a form element new FormData(form) returns us an iterator.
// [["key1", "val1"],["key2", "val2"]]
console.log([new FormData(form)...])
I would now like to convert this to an object of the form:
{ "key1": "val1", "key2": "val2" }
Using ES6/7 features (supported by babel).
Any ideas if this is possible to do in a functional approach?
Solution 1:[1]
You can use for..of loop
var formData = new FormData();
formData.append("a", 123);
formData.append("b", 456);
var obj = {};
for(let prop of formData) {obj[prop[0]] = prop[1]};
console.log(obj)
Alternatively, using rest element, FormData() which returns an Iterator, Array.prototype.forEach().
var formData = new FormData();
formData.append("a", 123)
formData.append("b", 456)
var res = (d, it = [...d], r = {}, t =!(it.forEach(([k, v]) => {r[k] = v}))) => r;
console.log(res(formData))
Solution 2:[2]
You can simply define an object and loop through the iterator to get the values from it and assign it to the object you created.
var fd = new FormData(someForm);
po = {};
for (var key of fd){
po[key] = fd[key];
}
Solution 3:[3]
using fuctional way
function getFormObj(form) {
return [...new FormData(form)].reduce((prev, [key,val]) => {
return Object.assign(prev, {[key] : val}) ;
}, {}) ;
}
Solution 4:[4]
It's an old question, but in recent times I think it can be solved using the following (just in case someone finds it useful):
let fd = new FormData(form)...
console.log(Array.from(fd.entries()))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Musa |
| Solution 3 | LKB |
| Solution 4 | FSp |
