“JavaScript -Klonobjekt” Code-Antworten

Klonobjekt in JS

var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));
JavascriptNinja

So erstellen Sie eine tiefe Kopie in JavaScript

JSON.parse(JSON.stringify(o))
Yuki

Objektklon JavaScript

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
Curious Chimpanzee

JavaScript -Klonobjekt

var x = {myProp: "value"};
var xClone = Object.assign({}, x);

//Obs: nested objects are still copied as reference.
Eranot

JavaScript -Klonobjekt

var sheep={"height":20,"name":"Melvin"};
var clonedSheep=JSON.parse(JSON.stringify(sheep));

//note: cloning like this will not work with some complex objects such as:  Date(), undefined, Infinity
// For complex objects try: lodash's cloneDeep() method or angularJS angular.copy() method
Grepper

Bester Weg, um ein Objekt in JavaScript zu klonen

const person = {
    firstName: 'John',
    lastName: 'Doe'
};


// using spread ...
let p1 = {
    ...person
};

// using  Object.assign() method
let p2 = Object.assign({}, person);

// using JSON
let p3 = JSON.parse(JSON.stringify(person));
Repulsive Raven

Ähnliche Antworten wie “JavaScript -Klonobjekt”

Fragen ähnlich wie “JavaScript -Klonobjekt”

Weitere verwandte Antworten zu “JavaScript -Klonobjekt” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen