Actually this is the interview question asked by Deloitte, Question is as follows
Suppose you have an object like
var obj={foo:"bar"}
Create a function cloneObject
method to clone the object example
var newObj=cloneObject(obj);
But the condition is
newObj==obj
should return true.newObj===obj
should return false.
Methods which I tried
var obj={foo:"bar"}
var newObj1=cloneObjectMethod1(obj)
var newObj2=cloneObjectMethod2(obj)
var newObj3=cloneObjectMethod3(obj)
var newObj4=cloneObjectMethod4(obj)
var newObj5=cloneObjectMethod5(obj)
//outputs
console.log(`From 1st Method: Double equals ${newObj1==obj} and Triple equals ${newObj1===obj}`)
console.log(`From 2nd Method: Double equals ${newObj2==obj} and Triple equals ${newObj2===obj}`)
console.log(`From 3rd Method: Double equals ${newObj3==obj} and Triple equals ${newObj3===obj}`)
console.log(`From 4th Method: Double equals ${newObj4==obj} and Triple equals ${newObj4===obj}`)
console.log(`From 5th Method: Double equals ${newObj5==obj} and Triple equals ${newObj5===obj}`)
function cloneObjectMethod1(obj){
return obj;
}
function cloneObjectMethod2(obj){
return Object.assign({}, obj);
}
function cloneObjectMethod3(obj){
return {...obj};
}
//I know this will never work as per my requirement
function cloneObjectMethod4(obj){
var o={};
Object.keys(obj).forEach(x=>{
o[x]=obj[x]
})
return o;
}
//I know this will never work as per my requirement
function cloneObjectMethod5(obj){
return JSON.parse(JSON.stringify(obj));
}
Could you please tell me how will I clone the object so my Double Equals will always true and Triple equals will always false
Thank You