-
[JavaScript] new FormData(form), Object.fromEntries(iterable), how to seriazlie form data컴퓨터/JavaScript_typescript 2021. 1. 31. 13:46
* forms with multiple fields that have the same name
* How to serialize form data with vanilla JS
1) FormData object
FormData object provides an easy way to serialize form fields into key/value pairs.
Form fields must have a name attribute to be includes object.
Otherwise, they're skipped.
<form id="post"> <label for="title">Title</label> <input type="text" name="title" id="title" value="Go to the beach"> <label for="body">Body</label> <textarea id="body" name="body">Soak up the sun and swim in the ocean.</textarea> <input type="hidden" name="userId" value="1"> <button>Submit</button> </form>
// Get the form let form = document.querySelector('#post'); // Get all field data from the form // returns a FormData object let data = new FormData(form);
* Looping through FormData
FormData object is an iterable -> for ... of loop로 looping through 가능
Each entry in the loop is an array of key/value pairs
// logs... // ["title", "Go to the beach"] // ["body", "Soak up the sun and swim in the ocean."] // ["userId", "1"] for (let entry of data) { console.log(entry); } // logs "title", "Go to the beach", etc. for (let [key, value] of data) { console.log(key); console.log(value); }
* FormData object의 method
[ set ]
FormData.set('date','July 4');
=> replace an existing entry, or add a new one if an entry with that key doesn't exist.
pass in the key and value as arguments.
[ append ]
// Add a second "body" key to the data FormData object data.append('body','Eat ice cream');
add a new entry.
If an item with that key already exists, another one is added and the existing one is unaffected.
[ delete ]
// Delete items with the "body" key data.delete('body');
If more than one item with that key exist, all of them are deleted.
* How to convert a FormData object into an object or query string
1) The FormData object can be submitted as-is to some endpoints with
a content-type header of multipart/form-data, not not all APIs support that.
2) new URLSearchParams()
: serialize a FormData object into a query string
This will create a URLSearchParams object of encoded query string values.
Then, call the URLSearchParams.toString() method on it to convert it into a query string.
// Get the form let form = document.querySelector('#post'); // Get all field data from the form let data = new FormData(form); // Convert to a query string let queryString = new URLSearchParams(data).toString();
3) To serialize a FormData object into a plain object, we need to loop through each entry with a for...of loop and add it to an object.
let obj = {}; for (let [key, value] of data) { if (obj[key] !== undefined) { if (!Array.isArray(obj[key])) { obj[key] = [obj[key]]; } obj[key].push(value); } else { obj[key] = value; } }
But, if there’s more one form field with the same name, the original value will get overwritten. To account for this, we need to check if the key already exists in the obj. If it does, we want to convert it to an array and Array.push() the new value into it.
function serialize (data) { let obj = {}; for (let [key, value] of data) { if (obj[key] !== undefined) { if (!Array.isArray(obj[key])) { obj[key] = [obj[key]]; } obj[key].push(value); } else { obj[key] = value; } } return obj; }
// Get the form let form = document.querySelector('#post'); // Get all field data from the form let data = new FormData(form); // Convert to an object let formObj = serialize(data);
* 간단한 방법으로는 Object.formEntries(iterable)가 있다
* Object.fromEntries(iterable)
- takes an iterable of key/value pairs and converts it into an array
// Get the FormData let form = document.querySelector('#post'); let data = new FormData(form); // Convert it into an object // returns {title: "Go to the beach", body: "Soak up the sun and swim in the ocean.", userId: "1"} let formObj = Object.fromEntries(data);
It’s important to note that the Object.fromEntries() method doesn’t work on all iterables. The iterable must represent a key/value pair.
That means it will work for FormData and Map(), but not for arrays or Set().
Should you use the Object.fromEntries() method?
The Object.fromEntries() method works in all modern desktop browsers, but not Opera Android or Samsung Internet (a mobile browser on many Samsung devices).
That might not seem like a bit deal, but Samsung Internet represents anywhere from 2.5% to 6.5% of total browser share. That’s potentially more than Firefox!
Fortunately, there’s a polyfill you can use.
/** * Object.entriesFrom() polyfill * @author Chris Ferdinandi * @license MIT */ if (!Object.entriesFrom) { Object.entriesFrom = function (entries){ if (!entries || !entries[Symbol.iterator]) { throw new Error('Object.fromEntries() requires a single iterable argument'); } let obj = {}; for (let [key, value] of entries) { obj[key] = value; } return obj; }; }
I had originally responded to a few folks that I would personally not use Object.fromEntries() until mobile browser support is better.
But after thinking about it more, I’d recommend using it today with a polyfill. The great thing about polyfills is that when browser support gets better, you can rip them out without having to refactor code.
source: gomakethings.com/how-to-serialize-form-data-with-vanilla-js/
gomakethings.com/the-object.fromentries-method-in-vanilla-js/
'컴퓨터 > JavaScript_typescript' 카테고리의 다른 글
Emmet + visual studio code extensions 추천 (0) 2021.03.22 개별 모듈로 분할하기: CommonJS vs ECMAScript module (0) 2021.02.18 [ JavaScrip ] 객체 생성 방식, OrdinaryObjectCreate (0) 2021.01.21 <script> 태그를 어디에 둘까, async, defer (0) 2020.12.11 [JavaScript] 같음 비교 (0) 2020.10.05