Mutating new object mutates the original object
Resolution: By Design
## Bug Report
After creating a new object with `deepmerge()`, if I update the new object, the original object gets updated as well.
### Expected behavior
No matter what I do to the new merged object, the original input objects should remain unmodified
### Actual behavior
Updating the new object also mutates the original objects
### Steps to reproduce
```typescript
import { deepmerge } from "deepmerge-ts";
import prettyFormat from "pretty-format";
const A = {
foo: {}
};
const B = {};
const newObject = deepmerge(A, B);
console.log("pre-modified A:", prettyFormat(A));
console.log("pre-modified newObject:", prettyFormat(newObject));
newObject.foo.bar = "a";
console.log("post-modified A:", prettyFormat(A));
console.log("post-modified newObject:", prettyFormat(newObject));
```
Output:
```
pre-modified A: Object {
"foo": Object {},
}
pre-modified newObject: Object {
"foo": Object {},
}
post-modified A: Object {
"foo": Object {
"bar": "a",
},
}
post-modified newObject: Object {
"foo": Object {
"bar": "a",
},
}
```
https://codesandbox.io/s/deepmerge-ts-example-forked-5f6kn6?file=/src/index.ts
The workaround I'm using now is to `structureClone()` the initial object first, like such:
```typescript
const newObject = deepmerge(structuredClone(A), B);
```
关闭于 2024-08-09 2 条评论