72
27

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 1 year has passed since last update.

ブラウザでディープコピーができるようになった

Last updated at Posted at 2022-02-03

Chrome98 で structuredCloneが来ました。
すでに Firefox では導入済みで、 Safari もプレビュー版で導入されているので、近い将来にメジャーブラウザでディープコピーが簡単にできるようになりそうです。 Safari 15.4 で実装されました。

structuredClone API | Can I use... Support tables for HTML5, CSS3, etc

const original = {
	x: 0,
	arr: [1, 2],
}

// 共有渡し
const sharing = original
//「浅い」コピー
const shallowCopy = {...original}
// ディープコピー
const deepCopy = structuredClone(original)

original.x = "x"
original.arr[0] = "x"

console.log(original)
// {x:"x", arr:["x",2]}

console.log(sharing)
// {x:"x", arr:["x",2]}

console.log(shallowCopy)
// {x:0, arr:["x",2]}

console.log(deepCopy)
// {x:0, arr:[1,2]}

なお、コピーできるオブジェクト|リテラルは限定されていますので注意が必要です。
構造化複製で動作しないもの | 構造化複製アルゴリズム - Web API | MDN


とはいえ、しばらくは lodash を使いそう。

72
27
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
72
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?