bodokaiser bodokaiser - 6 months ago 18
Javascript Question

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?

Answer

You can .reduce the Array made by using the spread ... operator

[...new FormData(document.querySelector('form'))].reduce((o, [k, v]) => {
    o[k] = v;
    return o;
}, {}); // Object {"key1": "val1", "key2": "val2"}
Comments