0
0

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 3 years have passed since last update.

javascriptで配列の要素がオブジェクトの場合に、全て値渡しでコピーしたいとき

Last updated at Posted at 2020-09-08

vue.js等を使っていると、dataに定義している配列を、参照渡しじゃなくて、値のみコピーしたい場合ってよくありますよね。

例. 下記のような配列の要素がオブジェクトの場合。

const array = [{a: 1}, {a: 2}]

下記のようにmapで各要素ごとをスプレッド構文で展開して、pushしていけばおk。

let newArray = []
array.map(a => {
  newArray.push({...a})
})

また、そのタイミングで、新しいプロパティを追加したい場合は、下記のようにすればおk

let newArray = []
array.map(a => {
  newArray.push({...a, b: 0})
})

もっといいコピーの仕方を知っている方がいれば教えて下さい!

0
0
6

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?