javascript オブジェクトのプロパティ値を変数を利用する
- 2020.10.02
- javascript
- javascript

javascriptで、オブジェクトのプロパティに変数名を使用するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
変数を利用
以下のように、記述することで変数を利用することができます。
1 2 3 4 5 6 7 |
const str = 'hoge'; const obj = { [str]: 'foo', }; console.log(obj); // {hoge: "foo"} |
また、以下のサンプルのようにも記述することも可能です。
1 2 3 4 5 |
const obj = { ['h'+'oge']: 'foo', }; console.log(obj); // {hoge: "foo"} |
関数を使用
1 2 3 4 5 |
const obj = { [function(){ return 'hoge' }()]: 'foo', }; console.log(obj); // {hoge: "foo"} |
オブジェクトを使用
1 2 3 4 5 6 7 |
const str = { toString: () => 'hoge' }; const obj = { [str]: 'foo', }; console.log(obj); // {hoge: "foo"} |
以下のように、記述することも可能です。
1 2 3 4 5 6 |
const str = 'hoge'; const obj = {}; obj[str] = 'foo', console.log(obj); |
サンプルコード
以下は、
「実行」ボタンをクリックすると、フォームから入力された値をプロパティとして使用したオブジェクトを表示する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> function hoge() { // フォームの値を取得 let str = document.getElementById('foo').value; // 変数にプロパティ値を設定 let propertyName = str; // プロパティ値に変数を利用 let obj = { [propertyName]: 'foo', }; // 表示用の要素を取得 let elm = document.getElementsByClassName("badge")[0]; // オブジェクトを表示 elm.textContent = JSON.stringify(obj); } window.onload = function () { // ボタンを取得 let elmbtn = document.getElementById('btn'); // クリックイベントを登録 elmbtn.onclick = function () { hoge(); }; } </script> <body> <div class="main container"> <h2><span class="badge bg-primary">オブジェクト表示</span></h2> <div class="row"> <div class="input-group mb-3"> <span class="badge bg-dark">プロパティ値</span> <input id="foo" type="text" class="form-control"> </div> </div> <div class="row"> <button id="btn" type="button" class="btn btn-warning"> 実行 </button> </div> </div> </body> </html> |
フォームの値が使用されていることが確認できます。

-
前の記事
dockerを使って「Apache Drill」を使用してみる 2020.10.02
-
次の記事
javascript 読み込んでいるcssを変更する 2020.10.02
コメントを書く