bodokaiser bodokaiser - 1 year ago 103
Javascript Question

How to convert a iterator (FormData) to an object

Given a

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 Source

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

[ FormData(document.querySelector('form'))].reduce((o, [k, v]) => {
    o[k] = v;
    return o;
}, {}); // Object {"key1": "val1", "key2": "val2"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download