I need to copy some properties of an object to another object and maintain its mutability.
Here is the source object:
var originalObj = {
"key1": "value1",
"key2": "value2",
"nestedObj1" : {
"nestedKey1" : "nestedValue1",
"nestedKey2" : "nestedValue2"
},
"nestedArr1" : [
{
"nestedKey3" : "nestedValue3",
"nestedKey4" : "nestedValue4"
},
{
"nestedKey5" : "nestedValue5",
"nestedKey6" : "nestedValue6"
}
],
"key3": "value3",
"key4": "value4"
}
Basically, I only need to copy the keys that are non-objects and non-arrays.
In this example, key1
, key2
, key3
and key4
So here is what I did:
var modObject = {}
Object.keys(originalObj).forEach((child) => {
// Copy non-objects and non-arrays
if (typeof originalObj[child] !== 'object' &&
!Array.isArray(modObject[child])) {
modObject[child] = originalObj[child]
}
})
// Change modObject and expect originalObj is updated to 'value3_modified' as well
modObject['key3'] = 'value3_modified'
console.log(originalObj['key3']) // Outputs 'value3' - Key3 value was not modified
console.log(modObject['key3']) // Outputs 'value3_modified'
But the problem is, when I update modObject
, its changes are not propagating to originalObj
. I know, this is because I am copying it as a value.
So I tried top copy the entire object and just delete the ones that should not be there (arrays and object keys):
// Copy the entire object
modObject = originalObj
Object.keys(modObject).forEach((child) => {
// Delete objects and arrays - these should not be in the new object
if (typeof modObject[child] === 'object' ||
Array.isArray(modObject[child])) {
delete modObject[child]
}
})
// Update modObject and expect originalObj updated to 'value3_modified' as well
modObject['key3'] = 'value3_modified'
console.log(modObject) // Outputs 'value3_modified'
console.log(originalObj) // // Outputs 'value3_modified' but object and array keys deleted in originalObj
But then, this time, my problem is since it is mutable, the keys that I deleted on the modObject
also gets deleted in originalObj
.
How can I achieve what I want:
- Copy non-object and non-array keys from
originalObj
tomodObject
while maintaining its mutability?
Here is my fiddle: https://jsfiddle.net/keechan/hbdj9mcs/11/
Help! Thanks!