I have been trying to deep clone a dynamic object in typescript and all methods just return an empty {}
object for this specific scenario!!
Here is the type of object I am trying to deep clone
fullValues: { [key : string ] : Array<string> },
NOTE: fullValues
is passed to a react component and the below mentioned operations happen in this react component! fullValues
is NEVER directly mutated throughout the lifecycle of the program and it is initially a state in the parent component as shown below:
const facetValues: { [key: string ] : Array<string> } = {};
// Type => facetedData?: FacetCollectionType
if (facetedData) {
Object.entries(facetedData).forEach(([key, value]) => {
Object.defineProperty(facetValues, key, { value: [] as string[]});
});
}
const [ facets, setFacets ] = useState<{ [key: string ] : Array<string> }>(facetValues);
{facetedData &&
Object.keys(facetedData).length !== 0 ?
Object.entries(facetedData).map(([key, options]) => (
<DataTableFacetedFilter
key={key}
options={options}
mainKey={key}
title={key}
fullValues={facets}
setSelectedValues={setFacets}
/>
))
:
null
}
Random example of how this object can be structured:
{
status: [],
plan: [],
}
I tried the following methods for deepcloning:
Using lodash deepclone
console.log(fullValues); // outputs { status: [], plan: [] }
console.log("after deep clone => ");
console.log(_cloneDeep(fullValues)); // outputs {}
Using JSON stringify method
console.log(fullValues); // outputs { status: [], plan: [] }
console.log("after deep clone => ");
console.log(JSON.parse(JSON.stringify(fullValues))); // outputs {}
However if I do this
let fullValues: { [key : string ] : Array<string> } = { status: [], plan: [] };
console.log(fullValues); // outputs { status: [], plan: [] }
console.log("after deep clone => ");
console.log(_cloneDeep(fullValues)); // outputs { status: [], plan: [] }
It works here.
There seems to be no logic to why this is happening? It makes no sense!