0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[メモ]FormDataオブジェクトにあるデータを全て削除する方法

Posted at

概要

FormDataにあるすべてのデータ(エントリー)を削除する

ポイント

formData.keys()やformData.entries()のイテレーター内で削除せず、イテレーターの外側で削除する。

FormDataオブジェクトのデータを全て削除する
function deleteAllFormData(formData) {
    const keys = [];
    for (const key of formData.keys()) {
        keys.push(key);
    }
    for (const idx in keys) {
        formData.delete(keys[idx]);
    }
}

サンプルコード(html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Delete all formdata</title>
</head>
<body>

<form action="#" method="post" id="myForm" enctype="multipart/form-data">
    <input type="hidden" name="myKey01" value="myValue01">
</form>
<script>

    function deleteAllFormData(formData) {
        const keys = [];
        for (const key of formData.keys()) {
            keys.push(key);
        }
        for (const idx in keys) {
            formData.delete(keys[idx]);
        }
    }

    const formData = new FormData(document.querySelector("#myForm"));
    formData.append("myKey02", "myValue02");
    formData.append("myKey03", "myValue03");

    console.log("Show form entries");
    for (const [key, value] of formData.entries()) {
        console.log(`key:${key} value:${value}`);
    }

    console.log("Delete!");
    deleteAllFormData(formData);

    console.log("Show form again");
    for (const [key, value] of formData.entries()) {
        console.log(`key:${key} value:${value}`);
    }


</script>

</body>
</html>
実行結果(ログ)
Show form entries
key:myKey01 value:myValue01
key:myKey02 value:myValue02
key:myKey03 value:myValue03
Delete!
Show form again

アンチパターン

反復中に自身を変更する以下のようなコードはアンチパターン

for (const key of formData.keys()) {
    formData.delete(key);
}

(Javaでも、同期リストのIteratorで反復中に自身を変更(削除も含む)するとConcurrentModificationExceptionが発生するパターン)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?