LoginSignup
5
3

More than 5 years have passed since last update.

オブジェクトのプロパティ名に変数や文字列展開を使用する

Posted at

ES6から[]で囲むことでオブジェクトのプロパティ名に変数や式を記述できるようです。
ただしオブジェクト初期化時のみ。

const hoge = "HOGE";
const obj = {
    [1 + 1]: "two",
    [hoge]: "just hoge",
    [`expand ${hoge}`]: "expand hoge"
};
console.log(JSON.stringify(obj,null,2));
結果
{
  "2": "two",
  "HOGE": "just hoge",
  "expand HOGE": "expand hoge"
}

参考

5
3
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
5
3