Javascript Object Cloning: Shallow Copies in {…x}
Here’s something that I learned today by digging into the links on Mark Erikson’s excellent comment on my post re: Adding/Editing/Removing items in an array.
The new Javascript spread operator (i.e. Object.assign) for objects const a = {...b}
only makes shallow copies of those objects. From the Redux docs:
function updateNestedState(state, action) {
// Problem: this only does a shallow copy!
let newState = {...state};
// ERROR: nestedState is still the same object!
newState.nestedState.nestedField = action.data;
return newState;
}
It looks like for a variety of reasons deep cloning is a non-trivial task, and there aren’t any easy hacks that don’t have some serious limitations. For example, the JSON hack…
let newState = JSON.parse(JSON.stringify(state))
… will dump the prototype chain and any methods on the object (according to this). And while I haven’t done anything more than some non-scientific browser testing using performance.now
on small test objects, it also seems like performance degrades somewhat linearly with the complexity of the object.
I imagine this is one of those problems Immutable.js solves.