how to duplicate an object in js 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

// 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 3: object clone 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 }