1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】Objectのプロパティ追加において動的なKeyを追加する方法

Posted at

Objectにプロパティを追加していく際にKeyを変数で作る際に躓いた過去の経験をもとに自身の備忘録として残しておこうと思う。

ObjectのプロパティKeyを動的にする追加方法

変数を用いて 動的なキー にしたい場合は ブラケット記法 を用いることで解決する。

単体の例

const key = 'email';
person[key] = 'taro@example.com';
console.log(person); // { age: 25, email: 'taro@example.com' }

ループ処理の例

const array = ['太郎', '次郎', '三郎'];
const objct = {};
array.forEach(function(element) {
  objct[element] = element;
});
console.log(objct);

JavaScript Objectのプロパティ追加方法まとめ

JavaScriptにはObjectにプロパティを追加する方法が複数存在する。

  1. ドット記法
  2. ブラケット記法
  3. Object.assign()を用いる記法
  4. スプレッド構文
    ※それぞれの使い方は下記の通り

✅ 1. ドット記法(dot notation)

const person = {};
person.name = '太郎';
console.log(person); // { name: '太郎' }

✅ 2. ブラケット記法(bracket notation)

const person = {};
person['age'] = 25;
console.log(person); // { age: 25 }

✅ 3. Object.assign() を使う方法

const person = {};
Object.assign(person, { gender: 'male' });
console.log(person); // { gender: 'male' }

✅ 4. スプレッド構文(新しいオブジェクトを作成)

const person = { name: '太郎' };
const updatedPerson = { ...person, age: 30 };
console.log(updatedPerson); // { name: '太郎', age: 30 }

※元のオブジェクトを変更せずに、新しいオブジェクトを作成したい場合に便利です。


誰かの参考になると嬉しい

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?