Serialize Form to JSON
JavaScript
Medium
3 views
Problem Description
You have a form #f and a
. On submit, prevent default and print JSON of all fields into #out. Multiple same-name fields should become an array.
Output Format
No output (DOM change).
Constraints
Assume #f form and #out exist.
Official Solution
const f=document.getElementById('f');const out=document.getElementById('out');f.addEventListener('submit',e=>{e.preventDefault();const fd=new FormData(f);const obj={};for(const [k,v] of fd.entries()){if(Object.prototype.hasOwnProperty.call(obj,k)){if(Array.isArray(obj[k]))obj[k].push(String(v));else obj[k]=[obj[k],String(v)];}else obj[k]=String(v);}out.textContent=JSON.stringify(obj,null,2);});
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!