1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptのスプレッド構文で、ArrayやObjectをマージ

Posted at

こちらの投稿コメントで、スプレッド構文(...)もつかえるとアドバイスを頂きましたのでまとめてみました。

スプレッド構文とは

Array や String などの iterable オブジェクトをその場で展開します
(引用元:https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Spread_syntax)

検索してサンプルを見ると配列を例にしている事が多いですが、実際にはObject({ })にも使用できます。

文法

ピリオド3つ(...)を展開したい物の前に記述します。

...Array
...Object

コード例

// 関数の引数
const array01 = [1, 2, 3];
MyFunction(...array01)
// 配列をマージ
const array02 = [10, 20, 30, 40];
const mergeArray = [...array01, ...array02];
// output [1,2,3,10,20,30,40]
// concantだと、[].concat(array01, array02);

// 配列に追加
let arr = [99, 999, 9999];
arr = [...arr, 10000];
// output [99,999,9999,10000]
// pushだと、arr.push(10000);

// コピー
const array03 = [...array02];
// objectをコピー
const object03 = {...object01};

//objectをマージ
const object01 = { foo: 'bar', x: 42 };
const object02 = { bar: 'baz', y: 13 };
const mergeObj = {...object01, ...object02};
/* 
output:
{
  "foo": "bar",
  "x": 42,
  "bar": "baz",
  "y": 13
}
*/

どんな時に使う?

初期化でオブジェクトをマージしたい時
データを加工したいとき(ユーザーからのinputで画面に表示させたいものを変化させるとか。)

注意したい事

ネストしているもの(多次元)には向かないです。
iterable オブジェクトだけに使えます。

参考

スプレッド構文
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Spread_syntax

JSのスプレッド演算子を理解する
https://qiita.com/akisx/items/682a4283c13fe336c547

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?