Object Clone code example

Example 1: clone object 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));

Example 2: clone javascript object

let clone = Object.assign({}, objToClone);

Example 3: javascript clone object

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

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

Example 4: how to clone an object

const first = {'name': 'alka', 'age': 21} 
const another = Object.assign({}, first);

Example 5: java clone method

int serial = 123;
MyObject thing1 = new MyObject(serial, "Name");
thing1.addDescription("The object I plan on cloning");

MyObject thing2 = thing1.clone();



@Override
public Object clone() throws CloneNotSupportedException {
	MyObject clone = new MyObject(this.serial, this.name); // All items were immutable
  	clone.description = new String(this.description); // If a field is not immutable
  	return clone;
}

Example 6: clone an object javascript

//returns a copy of the object
function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}