LoginSignup
0
0

js プロパティの呼び出し時にキー名に変数を使う

Posted at

概要

  • プロパティ呼び出し時のキー指定で変数を使う方法を簡単にまとめる

方法

  • オブジェクト内のプロパティ呼び出しにはドット記法とブラケット記法の2種類がある。キー指定で変数を使う場合、はブラケット記法になる。

  • 下記のようなオブジェクトが存在していたとする。

    let infos = {
        'hoge' : {
            'id' : 1,
            'name' : 'ほげ'
        },
        'fuga' : {
            'id' : 2,
            'name' : 'ふが',
        }
    }
    
  • infosのhogeのidの値を呼び出したい場合、下記のようになる。

    • ドット記法(念のため)

      console.log(infos.hoge.id);
      
    • ブラケット記法

      console.log(infos['hoge']['id']);
      
  • キーhogeを変数prefixに格納してブラケット記法で呼び出してみる。

    let infos = {
        'hoge' : {
            'id' : 1,
            'name' : 'ほげ'
        },
        'fuga' : {
            'id' : 2,
            'name' : 'ふが',
        }
    };
    
    const prefix = 'hoge';
    console.log(infos[prefix]['id']);
    
0
0
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
0