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で配列をディープコピーしたい

Last updated at Posted at 2019-12-05

はじめに

フロントエンドエンジニア1年目の新人プログラマーです。

以下、自分の勉強と備忘録に記録しておきます。参考になれば幸いです。

困ったこと

JavaScriptの配列をコピーするだけならいろいろな方法がありますが、
私が困ったのは以下のケースです。

const array1 = [{a:1, b:2}, {a:10,b:12}]

array1は維持したまま、各要素のbだけを変更したい

これを単純に値渡しすると、うまくいきません。

const array2 = array1.concat()

array2.forEach(x => x.b = null)
console.log(array2)
// (2) [{…}, {…}]
 0: {a: 1, b: null}
 1: {a: 10, b: null}

console.log(array1)
// (2) [{…}, {…}]
 0: {a: 1, b: null}
 1: {a: 10, b: null}

どうやら配列[] 自体は値コピーできていても、各要素は同じ参照になっているのでうまくいかないそうです。

解決策

なので各要素も値コピーするために、次の実装が良さそうです。

const array2 = array1.map(x => {
                const y = {};
                Object.assign(y,x);
                return y;});

array2.forEach(x => x.b = null)
console.log(array2)
// (2) [{…}, {…}]
 0: {a: 1, b: null}
 1: {a: 10, b: null}

console.log(array1)
// (2) [{…}, {…}]
 0: {a: 1, b: 2}
 1: {a: 10, b: 12}

まとめ

言語によっては仕様が違うかもしれませんが、javaScriptにおいては上記の実装で解決できました。

1
1
4

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?