Javascript
 Computer >> コンピューター >  >> プログラミング >> Javascript

javascriptの1つのキーを除いてjsオブジェクトのクローンを作成するにはどうすればよいですか?


1つのキーを除いてオブジェクトのクローンを作成する最も簡単な方法は、オブジェクト全体のクローンを作成してから、不要なプロパティを削除することです。ただし、クローニングには2つのタイプがあります-

  • ディープクローン
  • 浅いクローン

浅いコピーは可能な限り複製しません。コレクションの浅いコピーは、要素ではなく、コレクション構造のコピーです。浅いコピーで、2つのコレクションが個々の要素を共有するようになりました。

let innerObj = {
   a: 'b',
   c: 'd'
}
let obj = {
   x: "test",
   y: innerObj
}
// Create a shallow copy.
let copyObj = Object.assign({}, obj);
// Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
innerObj.a = "test"
console.log(obj)
console.log(copyObj)
This will give the output:
{ x: 'test', y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'test', c: 'd' } }

浅いコピーは再帰的にクローンを作成しないことに注意してください。トップレベルでそれを行うだけです。

ディープコピーはすべてを複製します。コレクションのディープコピーは、元のコレクションのすべての要素が複製された2つのコレクションです。

let innerObj = {
   a: 'b',
   c: 'd'
}
let obj = {
   x: "test",
   y: innerObj
}
// Create a deep copy.
let copyObj = JSON.parse(JSON.stringify(obj))
// Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
innerObj.a = "test"
console.log(obj)
console.log(copyObj)
This will give the output:
{ x: 'test', y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'b', c: 'd' } }

これらの方法のいずれかを使用してコピーを取得したら、deleteキーワードを使用して不要なプロパティを削除できます。たとえば、

let original = { x: 'test', y: { a: 'test', c: 'd' } }
let copy = JSON.parse(JSON.stringify(original))
delete copy['x']
console.log(copy)
console.log(original)
This will give the output:
{ y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'test', c: 'd' } }

  1. 1つのキーなしでオブジェクトを分解する

    以下は、1つのキーなしでオブジェクトを非構造化するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>   &

  2. JavaScriptでオブジェクトごとに一意のIDを作成するにはどうすればよいですか?

    以下は、オブジェクトごとに一意のIDを作成するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>