LoginSignup
0
0

More than 1 year has passed since last update.

オブジェクトの拡張方法

Posted at

JavaScriptであるオブジェクトから別のオブジェクトにプロパティをコピーする方法のメモ。

let target = { x: 1 },
  source = { y: 2, z: 3 };
for (let key of Object.keys(source)) {
  target[key] = source[key];
}
target // { x: 1, y: 2, z: 3 }

上のコードではtargetにsourceのオブジェクトをコピーできる。ですが、ES6からは新しいメソッドが追加されている。

let target = { x: 1, y: 2 },
  source = { y: 3, z: 4 };
Object.assign(target, source);
target // { x: 1, y: 3, z: 4 }

Object.assign()メソッドである。ただし、これはすでにオブジェクトに同じ名前のプロパティが定義されていた場合はそれも上書きされてしまいます。それを防ぎたい場合は次のように書く。

target = Object.assign({},source,target)
target // { x: 1, y: 2, z: 4 }

新しいオブジェクトを生成し、そこにsource、をコピー、targetで上書きします。またこのような処理は次のようにスプレッド演算子(...)を使用しても同様に処理が可能。

target = { ...source, ...target };
target // { x: 1, y: 2, z: 4 }

勉強した本

0
0
1

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