how to clone an object 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: javascript clone object

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

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

Example 3: how to clone an object

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

Example 4: javascript clone object

let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));

Example 5: javascript clone object

// syntax: let <newObjectName> = {...<initialObjectName>};

// example: 
const me = {
  name: 'Jakes',
  age: 30,
};
const friend = {...me};
friend.age = 27;
console.log(friend.age); // 27
console.log(me.age); // 30

// -----------------------------
//  BAD
// -----------------------------
const me = {
  name: 'Jonas',
  age: 30,
};
const friend = me;
friend.age = 27;
console.log(friend.age); // 27
console.log(me.age); // 30

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;
}