LoginSignup
15
9

More than 5 years have passed since last update.

[js]配列のコピー

Last updated at Posted at 2017-12-15

はじめに

reduxのstateで配列のコピーがうまくできておらず、勝手にstateが更新されてはまったのでメモ

参照渡し

こちらの記事を読めばわかるが、jsの配列はobjectの一種でobjectと同じ参照渡しである。
そのため、普通に変数に入れて値を更新するると、参照先の値も変更されてしまう。

const itemArr = [
  {id: 1, value: 10},
  {id: 2, value: 100},
]

const newItemArr = itemArr
newItemArr[1].value = 200

console.log(itemArr[1].value) // 200
console.log(newItemArr[1].value) // 200

shallow clone

concatやsliceを使うと配列自体はコピーされるが、その中のobjectは参照渡しになってしまう。

const itemArr = [
  {id: 1, value: 10},
  {id: 2, value: 100},
]

const newItemArr = itemArr.concat()
newItemArr[0] = 1
newItemArr[1].value = 200

console.log(itemArr[0]) // {id: 1, value: 10}
console.log(itemArr[1].value) // 200

deep clone

外部のライブラリーを使うことでobjectの値までコピーすることができる。参考

lodash

lodashのcloneDeepを使うと簡単に実装できる。

import _ from 'lodash'

const itemArr = [
  {id: 1, value: 10},
  {id: 2, value: 100},
]

const newItemArr = _.cloneDeep(itemArr)
newItemArr[0] = 1
newItemArr[1].value = 200

console.log(itemArr[0]) // {id: 1, value: 10}
console.log(itemArr[1].value) // 100
15
9
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
15
9