how to create clone of an object in javascript 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: best way to clone an object in javascript
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));