はじめに
フロントエンドエンジニア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においては上記の実装で解決できました。