javascript オブジェクトからURLパラメーターを生成する

javascript オブジェクトからURLパラメーターを生成する

javascriptで、オブジェクトからURLパラメーターを生成するサンプルコードを記述してます。「URLSearchParams」を使用すれば簡単に生成することが可能です。オブジェクトだけではなく配列からも生成することが可能です。

環境

  • OS windows11 home
  • ブラウザ chrome 107.0.5304.88

URLパラメーターを生成

URLパラメーターを生成するには、「URLSearchParams」を使用するだけで可能です。

const obj = {
  page: 5,
  word: 'mebee',
  limit: 20,
};

const result = '?' + new URLSearchParams(obj).toString();

console.log(result); // ?page=5&word=mebee&limit=20

「配列」にも使用できます。

const arr = [['page', 5],['word', 'mebee'],['limit', 20]];

const result = '?' + new URLSearchParams(arr).toString();

console.log(result); // ?page=5&word=mebee&limit=20

URLパラメーターからオブジェクトに変換

逆に、オブジェクトに変換するには「Object.fromEntries」を使用して「URLSearchParams」からオブジェクト化します。

const str = "?page=5&word=mebee&limit=20";

let result = new URLSearchParams(str);

console.log(result.get('page')); // 5
console.log(result.get('word')); // mebee

result = Object.fromEntries(new URLSearchParams(str));

console.log(result); // {page: '5', word: 'mebee', limit: '20'}

サンプルコード

以下は、実行ボタンをクリックすると、用意したオブジェクトからURLパラメーターに変換して表示するだけのサンプルコードとなります。

※cssには「Material Design for Bootstrap」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-75 mx-auto" style="margin-top:200px">

    <h2><span class="badge badge-info">最初に見つかった値</span></h2>
    <h2><span class="badge badge-info">結果</span></h2>

    <button type="button" onclick="hoge()" class="btn btn-raised btn-danger">
      取得
    </button>

  </div>

  <script>

    const hoge = () => {

      // ランダムな数値(0~9)をvalueにもつオブジェクトを生成
      let obj = { num1: Math.floor(Math.random() * 10), num2: Math.floor(Math.random() * 10), num3: Math.floor(Math.random() * 10) };

      // JSON 文字列に変換してオブジェクトを表示
      document.getElementsByClassName("badge")[0].textContent = JSON.stringify(obj);

      // パラメータを表示
      document.getElementsByClassName("badge")[1].textContent = '?' + new URLSearchParams(obj).toString();

    }

  </script>
</body>

</html>

変換されていることが確認できます。