Since you updated your question then: now I guess you would prefer to not use Object.assign at all. What you seem to want because you want even the name of "copy
" to be changed when "original
" gets updated is to set copy to be a reference/pointer to the same object that original references
You can simply: set const copy = original
to get that result.
const original = {
name: 'porsche',
car: { color: 'green' }
}
const copied = original
original.name = 'Lamborghini'
document.write(copied.name)
// despite copied being a "copy" of original... it gets all the updates that original gets.
// That's because copy is not a copy at all but rather a pointer just like original is a pointer and they both point to the same object in the heap of memory.
you can have multiple pointers to the same space in memory/object which will allow you to modify one of the pointer's key and then it will change it for all pointers. This is assignment to the reference.
This is regarding why Object.assign is not a deep clone:
So that is because the object contains only a reference to the pointer to the nested object.
Specifically,
The object:
{
color: 'blue'
}
Is an object that you did not apply Object.assign to... so by having: color: "0xC32332"
"0xC32332" is the pointer to the space in memory which contains the object with the key color and the current value blue.
When doing Object.assign you are not changing the value -from the key car
(aka the object) you are just creating a new pointer to the same object/space in memory.
So if you want to do a "deep" clone using Object.assign()
you have to call it recursively.
const recursiveDeep = (obj) => {
return Object.keys(obj).reduce((newObj, currentKey) => {
if (typeof obj[currentKey] === 'object'){
newObj[currentKey] = recursiveDeep(obj[currentKey])
}
else {
newObj[currentKey] = obj[currentKey]
}
return newObj
}, {})
}
const original = {
name: 'porsche',
car: { color: 'green' }
}
const copied = recursiveDeep(original)
original.name = 'Lamborghini'
original.car.color = 'red'
document.write(copied.name)
document.write(copied.car.color)