how to clone an object javascript code example
Example 1: clone object in js
var student = {name: "Rahul", age: "16", hobby: "football"};
var studentCopy1 = Object.assign({}, student);
var studentCopy2 = {...student};
var studentCopy3 = JSON.parse(JSON.stringify(student));
Example 2: clone javascript object
let clone = Object.assign({}, objToClone);
Example 3: how to clone an object
const first = {'name': 'alka', 'age': 21}
const another = Object.assign({}, first);
Example 4: javascript clone object
var sheep={"height":20,"name":"Melvin"};
var clonedSheep=JSON.parse(JSON.stringify(sheep));
Example 5: clone an object javascript
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;
}
Example 6: object clone javascript
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
console.log(returnedTarget);