const userDetails = {
name: "John Doe",
age: 14,
verified: false
};
//1. using Equality **********************impact the parent*********************//
// const newUser = userDetails;
// newUser.name= "Abhishek";
// console.log('Created using equality',newUser);
// console.log('Main object',userDetails);
//2. using Spread ***************doesnt impact the parent****************************//
// let cloneUser = { ...userDetails };
// console.log('clone user',cloneUser);
// cloneUser.name = "Abhishek"
// console.log('clone user',cloneUser);
// console.log('main user after chaning clone',userDetails);
// 3. Cloning the Object with Object.assign() Method***********
// let assignObj = Object.assign({}, userDetails);
// console.log('assign object',assignObj);
// assignObj.name = "Abhishek"
// console.log('assign user after change',assignObj);
// console.log('main user after chaning clone',userDetails);
//4. Cloning the object using JSON.parse
const deepObj = {
name: "John Doe",
age: 14,
status: {
verified: false,
}
};
//Isssue- the assign and spread will impact the deep objects
// let spreadUser={...deepObj};
// spreadUser.status.verified=true;
// console.log('Spread user',spreadUser);
// console.log('deep user',deepObj);
//Hence use JSON
// let deepclone=JSON.parse(JSON.stringify(deepObj));
// deepclone.status.verified=true;
// console.log('deep clone ',deepclone);
// console.log('deep user',deepObj);
//6. ISSUE WIth DEep Clone- it will impact functions and skip undefined varables
const Deepobjects = {
name: "John Doe",
age: 14,
status: {
verified: false,
method: function(){
console.log('In object function')
},
title: undefined,
}
};
// Cloning the Object with Spread Operator
let jsonobject = JSON.parse(JSON.stringify(Deepobjects));
console.log(jsonobject);