Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The second object was changed when the first is "{}" #14

Open
cczw2010 opened this issue Mar 23, 2022 · 3 comments · May be fixed by #15
Open

The second object was changed when the first is "{}" #14

cczw2010 opened this issue Mar 23, 2022 · 3 comments · May be fixed by #15

Comments

@cczw2010
Copy link

The Code:

import mixinDeep from "mixin-deep"
const a = {a:{a:1,b:0}};
const b = {a:{b:2},b:1};
const c = {a:{a:2},c:2};
const d = mixinDeep({},a,b,c);
console.log("a",a)
console.log("b",b)
console.log("c",c)
console.log("d",d)

The console output:

a { a: { a: 2, b: 2 } }
b { a: { b: 2 }, b: 1 }
c { a: { a: 2 }, c: 2 }
d { a: { a: 2, b: 2 }, b: 1, c: 2 }

why "a" is changed,

@maiermic
Copy link

maiermic commented May 29, 2022

Because objects are not cloned, when they are assigned. See the added log at the end:

import mixinDeep from "mixin-deep"
const a = {a:{a:1,b:0}};
const b = {a:{b:2},b:1};
const c = {a:{a:2},c:2};
const d = mixinDeep({},a,b,c);
console.log("a",a)
console.log("b",b)
console.log("c",c)
console.log("d",d)
console.log("d.a === a.a", d.a === a.a)

I suppose to change

target[key] = val;
to

target[key] = mixinDeep({}, val);

in case isObject(val).

Note: This does not clone arrays.

@cczw2010
Copy link
Author

cczw2010 commented Jun 8, 2022

Thanks for the reply

@cloudrac3r cloudrac3r linked a pull request Aug 23, 2023 that will close this issue
@cloudrac3r
Copy link

I hit this too and thought it was a bug, but this behaviour is actually specified in the tests. I found this unintuitive and unpredictable, so I created PR 15 to make it work the way I expected.

If you need to use my version before Jon merges my pull request, you can install it using the command npm install cloudrac3r/mixin-deep#v3.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants